Confusing Number II in C++


Suppose we have a digit, now if we rotate that digit by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. But when 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.

A confusing number is a number that when rotated 180 degrees becomes a new number. So, if we have a positive integer N, we have to find the number of confusing numbers between 1 and N inclusive.

So, if the input is like 20, then the output will be 6

To solve this, we will follow these steps −

  • Define one map mapping

  • Define an array valid

  • Define a function solve(), this will take num, rotate, digit, N,

  • if rotate is not equal to num, then −

    • (increase ret by 1)

  • for initialize i := 0, when i < size of valid, update (increase i by 1), do −

    • dig := valid[i]

    • if num * 10 + dig > N, then

      • Come out from the loop

    • solve(num * 10 + dig, Define one map, digit * 10, N)

  • From the main method do the following −

  • ret := 0

  • valid := { 0, 1, 6, 8, 9 }

  • mapping[0] := 0

  • mapping[1] := 1

  • mapping[6] := 9

  • mapping[9] := 6

  • mapping[8] := 8

  • solve(1, 1, 10, N)

  • solve(6, 9, 10, N)

  • solve(9, 6, 10, N)

  • solve(8, 8, 10, N)

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int ret;
   map <int, int> mapping;
   vector <int> valid;
   void solve(lli num, lli rotate, lli digit, lli N){
      if (rotate != num) {
         ret++;
      }
      for (int i = 0; i < valid.size(); i++) {
         int dig = valid[i];
         if (num * 10 + dig > N) {
            break;
         }
         solve(num * 10 + dig, mapping[dig] * digit + rotate, digit * 10, N);
      }
   }
   int confusingNumberII(int N) {
      ret = 0;
      valid = { 0, 1, 6, 8, 9 };
      mapping[0] = 0;
      mapping[1] = 1;
      mapping[6] = 9;
      mapping[9] = 6;
      mapping[8] = 8;
      solve(1, 1, 10, N);
      solve(6, 9, 10, N);
      solve(9, 6, 10, N);
      solve(8, 8, 10, N);
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.confusingNumberII(20));
}

Input

20

Output

6

Updated on: 11-Jul-2020

608 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements