Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Jul, 2022

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:

 

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)


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)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!