Open In App

Count numbers in given range which are symmetrical when rotated 180 degree clockwise

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a range [L, R), the task is to count the numbers that remain unchanged when rotated 180 degrees clockwise.

Examples:

Input: L = 0, R =10 
Output: 3
Explanation: Here between 0 and 10 ( 10 exclusive) the desired numbers are: 0, 1, and 8. 
Notice 6 and 9 are not included because, when 6 is rotated 180 degree it’s value changes to 9.
Same happens for 9, its value changes to 6. So the answer is 3.

Input: L = 0, R =100 
Output: 7
Explanation: The numbers are 0, 1, 8, 11, 69, 88, 96. 
These numbers when rotated 180 degrees, their values remain unchanged.

 

Approach: This approach is implementation based. Use a function to check whether a number is upside number or not and iterate over the range and calculate the total numbers satisfying the given condition.

  • Initialize “result” variable with 0.
  • First iterate over the range [L, R).
  • Keep a dictionary which has all the single-digit numbers which form a valid number when rotated 180 degrees.(like 6 becomes 9)
  • At each iteration check whether the number satisfies the given condition of the problem:
    • Check whether the digits of a number are in dictionary or not.
    • If not then return False.
    • If It is part of the dictionary then check its opposite indexed element is same or not.
      • If not then return False.
    • If everything matches then return true.
  • If It is, then increment “result” variable by 1.

Below is the implementation of the above approach.

C++




// C++ program to implement the approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to check if a number is same
// when rotated 180 degrees
bool Check_Upside_Down(string n){
  unordered_map<char,char> Dict;
  Dict['0'] = '0';
  Dict['1'] = '1';
  Dict['6'] = '9';
  Dict['8'] = '8';
  Dict['9'] = '6';
 
  for(int x = 0; x < n.length(); x++) {
 
    if (Dict.find(n[x]) == Dict.end())
      return false;
    if (Dict[n[x]] != n[n.length() - x - 1])
      return false;
  }
  return true;
}
 
// Function to find total count of numbers
// having same value when rotated 180 degrees
int Total_Upside_Number(int L,int R){
  int res = 0;
  for (int i = L; i < R; ++i){
    if (Check_Upside_Down(to_string(i)))
      res += 1;
  }
  return res;
}
 
// Driver code
int main(){
 
  int L = 0;
  int R = 10;
  int ans = Total_Upside_Number(L, R);
  cout << ans << endl;
 
}
 
// This code is contributed by shinjanpatra


Java




// Java program to implement the approach
import java.util.*;
 
class GFG{
 
// Function to check if a number is same
// when rotated 180 degrees
static boolean Check_Upside_Down(String n){
   
  HashMap<Character,Character> Dict = new HashMap<Character,Character>();
  Dict.put('0', '0');
  Dict.put('1', '1');
  Dict.put('6', '9');
  Dict.put('8', '8');
  Dict.put('9', '6');
 
  for(int x = 0; x < n.length(); x++) {
 
    if (!Dict.containsKey(n.charAt(x)))
      return false;
    if (Dict.get(n.charAt(x))!= n.charAt(n.length() - x - 1))
      return false;
  }
  return true;
}
 
// Function to find total count of numbers
// having same value when rotated 180 degrees
static int Total_Upside_Number(int L,int R){
  int res = 0;
  for (int i = L; i < R; ++i){
    if (Check_Upside_Down(String.valueOf(i)))
      res += 1;
  }
  return res;
}
 
// Driver code
public static void main(String[] args){
 
  int L = 0;
  int R = 10;
  int ans = Total_Upside_Number(L, R);
  System.out.print(ans +"\n");
 
}
 
}
// This code contributed by shikhasingrajput


Python




# Python program to implement the approach
 
# Function to check if a number is same
# when rotated 180 degrees
def Check_Upside_Down(n):
    Dict = {"0": "0", "1": "1", "6": "9", \
            "8": "8", "9": "6"}
    for x, y in enumerate(n):
        if y not in Dict:
            return False
        if Dict[y] != n[-x-1]:
            return False
    return True
 
# Function to find total count of numbers
# having same value when rotated 180 degrees
def Total_Upside_Number(L, R):
    res = 0
    for i in range(L, R):
        if Check_Upside_Down(str(i)):
            res += 1
    return res
 
# Driver code
if __name__ == "__main__":
    L = 0
    R = 10
    ans = Total_Upside_Number(L, R)
    print(ans)


C#




// C# program to implement the approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
// Function to check if a number is same
// when rotated 180 degrees
static bool Check_Upside_Down(String n){
   
  Dictionary<char,char> Dict = new Dictionary<char,char>();
  Dict.Add('0', '0');
  Dict.Add('1', '1');
  Dict.Add('6', '9');
  Dict.Add('8', '8');
  Dict.Add('9', '6');
 
  for(int x = 0; x < n.Length; x++) {
 
    if (!Dict.ContainsKey(n[x]))
      return false;
    if (Dict[n[x]]!= n[n.Length - x - 1])
      return false;
  }
  return true;
}
 
// Function to find total count of numbers
// having same value when rotated 180 degrees
static int Total_Upside_Number(int L,int R){
  int res = 0;
  for (int i = L; i < R; ++i){
    if (Check_Upside_Down(String.Join("",i)))
      res += 1;
  }
  return res;
}
 
// Driver code
public static void Main(String[] args){
 
  int L = 0;
  int R = 10;
  int ans = Total_Upside_Number(L, R);
  Console.Write(ans +"\n");
 
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
    // JavaScript program to implement the approach
 
    // Function to check if a number is same
    // when rotated 180 degrees
    const Check_Upside_Down = (n) => {
        let Dict = { "0": "0", "1": "1", "6": "9", "8": "8", "9": "6" }
        for (let x = 0; x < n.length; ++x) {
            if (!(n[x] in Dict))
                return false;
            if (Dict[n[x]] != n[n.length - x - 1])
                return false;
        }
        return true;
    }
 
    // Function to find total count of numbers
    // having same value when rotated 180 degrees
    const Total_Upside_Number = (L, R) => {
        let res = 0
        for (let i = L; i < R; ++i)
            if (Check_Upside_Down(i.toString()))
                res += 1
        return res
    }
 
    // Driver code
    let L = 0;
    let R = 10;
    let ans = Total_Upside_Number(L, R);
    document.write(ans);
 
// This code is contributed by rakeshsahni
 
</script>


 
 

Output

3

 

Time Complexity: O((R – L)*d) where d is the maximum number of digits in a number in the range [L, R)
Auxiliary Space: O(1)

 

Using maketras() and translate(): The overhead with above method is that we have to write the method which iterate over number and check one by one that it is same when rotated 180 degrees. In Python some methods make this transition easy to code. In this approach use maketras() and translate() function of string which eases the work. 

 

  1. Have set s1 of all the single digit numbers which give another valid number when rotated 180 degrees.
  2. Have transition table which is prepared with suitable number for it’s replacement.
  3. Iterate over the range [L, R).
  4. At each iteration convert number to set of character.
  5. Check whether the set is a subset of s1 or not.
  6. If it is not then continue iteration.
  7. If it is subset of s1 then:
    1. Translate all the numbers with the help of transition table.
    2. Then match it with previous number.
    3. If it does not match, continue iteration.
    4. if matches then increase count by 1.

 

Below is the implementation of the above approach:

 

C++




// C++ program to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// maketrans() in C++
std::function<std::string(std::string)>
maketrans(const std::string& from, const std::string& to) {
    std::unordered_map<char, char> map;
    for (std::string::size_type i = 0;
         i != std::min(from.size(), to.size()); ++i) {
        map[from[i]] = to[i];
    }
    return [=](std::string s) {
        for (auto& c : s) {
            const auto mapped_c = map.find(c);
            if (mapped_c != map.end()) {
                c = mapped_c->second;
            }
        }
        return s;
    };
}
 
// Function to calculate the total count
// of required numbers using
// maketrans() and translate()
int Total_Upside_number(int L, int R){
    string s1[] = {"0", "1", "6", "8", "9"};
    int n= sizeof(s1) / sizeof(s1[0]);
    auto translate = maketrans("69", "96");
    int result = 0;
    for(int i=L;i<R;i++){
        string num = to_string(i);
        if(find(s1, s1 + n, num) != s1 + n)
                  {
            reverse(num.begin(),num.end());
            string temp=translate(num);
            if (num == temp){
                result += 1;
            }
        }
    }
    return result;
}
 
// Driver code
int main()
{
    int L = 0;
    int R = 10;
    int ans = Total_Upside_number(L, R);
    cout<<(ans);
}
 
// This code is contributed by Aman Kumar


Java




// Java program to implement the approach
import java.util.*;
import java.util.function.*;
 
class GFG {
 
  public static Function<String, String> maketrans(final String from, final String to) {
    final Map<Character, Character> map = new HashMap<>();
    final int length = Math.min(from.length(), to.length());
    for (int i = 0; i < length; i++) {
      map.put(from.charAt(i), to.charAt(i));
    }
    return (final String s) -> {
      final StringBuilder builder = new StringBuilder();
      for (final char c : s.toCharArray()) {
        final Character mappedC = map.get(c);
        if (mappedC != null) {
          builder.append(mappedC);
        } else {
          builder.append(c);
        }
      }
      return builder.toString();
    };
  }
  // Function to calculate the total count
// of required numbers using
// maketrans() and translate()
  public static int totalUpsideNumber(final int L, final int R) {
    final String[] s1 = {"0", "1", "6", "8", "9"};
    final Function<String, String> translate = maketrans("69", "96");
    int result = 0;
    for (int i = L; i < R; i++) {
      final String num = Integer.toString(i);
      if (Arrays.asList(s1).contains(num)) {
        final String reversedNum = new StringBuilder(num).reverse().toString();
        final String temp = translate.apply(reversedNum);
        if (num.equals(temp)) {
          result++;
        }
      }
    }
    return result;
  }
 
  public static void main(final String[] args) {
    final int L = 0;
    final int R = 10;
    final int ans = totalUpsideNumber(L, R);
    System.out.println(ans);
  }
}


Python3




# Python program to implement the approach
 
# Function to calculate the total count
# of required numbers using
# maketrans() and translate()
def Total_Upside_number(L, R):
    s1 = {"0", "1", "6", "8", "9"}
    transition = str.maketrans("69", "96")
    result = 0
    for i in range(L, R):
        num = str(i)
        if set(num).issubset(s1):
            temp = num[::-1].translate(transition)
            if num == temp:
                result += 1
    return result
 
# Driver code
if __name__ == "__main__":
    L = 0
    R = 10
    ans = Total_Upside_number(L, R)
    print(ans)


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
 
  // maketrans() in C#
  public static Func<string, string> maketrans(string fromStr, string toStr) {
    Dictionary<char, char> map = new Dictionary<char, char>();
    for (int i = 0; i < Math.Min(fromStr.Length, toStr.Length); ++i) {
      map[fromStr[i]] = toStr[i];
    }
    return s => new string(s.Select(c => map.ContainsKey(c) ? map : c).ToArray());
  }
 
  // Function to calculate the total count of required numbers
  // using maketrans() and translate()
  public static int Total_Upside_number(int L, int R) {
    string[] s1 = { "0", "1", "6", "8", "9" };
    int n = s1.Length;
    var translate = maketrans("69", "96");
    int result = 0;
    for (int i = L; i < R; i++) {
      string num = i.ToString();
      if (s1.Contains(num)) {
        num = new string(num.Reverse().ToArray());
        string temp = translate(num);
        if (num == temp) {
          result += 1;
        }
      }
    }
    return result;
  }
 
  // Driver code
  static void Main(string[] args) {
    int L = 0;
    int R = 10;
    int ans = Total_Upside_number(L, R);
    Console.WriteLine(ans);
  }
}


Javascript




// Define a function to make a translation map
function makeTrans(from, to) {
let map = {};
let length = Math.min(from.length, to.length);
for (let i = 0; i < length; i++) {
map[from[i]] = to[i];
}
return (s) => {
let result = "";
for (let i = 0; i < s.length; i++) {
let mappedC = map[s[i]] ? map[s[i]] : s[i];
result += mappedC;
}
return result;
};
}
 
// Function to calculate the total count
// of required numbers using
// makeTrans() and translate()
function totalUpsideNumber(L, R) {
let s1 = ["0", "1", "6", "8", "9"];
let translate = makeTrans("69", "96");
let result = 0;
for (let i = L; i < R; i++) {
let num = i.toString();
if (s1.includes(num)) {
let reversedNum = num
.split("")
.reverse()
.join("");
let temp = translate(reversedNum);
if (num === temp) {
result++;
}
}
}
return result;
}
 
// Test the function
let L = 0;
let R = 10;
let ans = totalUpsideNumber(L, R);
console.log(ans);


Output

3

Time Complexity: O((R – L)*d) where d is the maximum number of digits in a number in the range [L, R)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads