Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Reordered Power of 2 in C++
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
#includeusing 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 Input
812Output
1
Advertisements
