Reordered Power of 2 in C++

C++Server Side ProgrammingProgramming

Suppose we have a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is non-zero. We have to check whether we can do this in a way such that the resulting number is a power of 2. So if the number is like 46, then the answer will be true.

To solve this, we will follow these steps −

  • Define a method called count, this will take x as input

  • ret := 0

  • while x is not 0

    • ret := ret + 10 ^ last digit of x

    • x := x / 10

  • return ret

  • From the main method do the following −

  • x := count(N)

  • for i in range 0 to 31

    • if count(2^i) = x, then return true

  • return false

Let us see the following implementation to get better understanding −

Example

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int count(int x){
      int ret = 0;
      while(x){
         ret += pow(10, x % 10);
         x /= 10;
      }
      return ret;
   }
   bool reorderedPowerOf2(int N) {
      int x = count(N);
      for(int i = 0; i < 32; i++){
         if(count(1 << i) == x) return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.reorderedPowerOf2(812));
}

Input

812

Output

1
raja
Published on 10-Apr-2020 09:32:10
Advertisements