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
-
Economics & Finance
Program to find Reordered Power of 2 in Python
Given a positive integer N, we need to check if we can reorder its digits to form a power of 2. The reordered number must have no leading zeros.
For example, if N = 812, we can rearrange it to 128, which is 2^7, so the answer is True.
Algorithm
To solve this problem, we will follow these steps ?
Start with i = 1 (which is 2^0)
-
While i ? 1000000000, do the following:
Convert i to string and sort its digits
Convert N to string and sort its digits
If both sorted strings are equal, return True
Multiply i by 2 to get the next power of 2
If no match is found, return False
Example
Let us see the following implementation to get better understanding ?
def solve(n):
i = 1
while i <= 1000000000:
# Convert power of 2 to string and sort digits
s = str(i)
s = ''.join(sorted(s))
# Convert input number to string and sort digits
t = str(n)
t = ''.join(sorted(t))
# Check if sorted digit sequences match
if s == t:
return True
# Move to next power of 2
i = i * 2
return False
# Test the function
N = 812
print(f"Can {N} be reordered to form a power of 2? {solve(N)}")
# Let's see what power of 2 it matches
print(f"812 can be rearranged to form: 128 = 2^7")
The output of the above code is ?
Can 812 be reordered to form a power of 2? True 812 can be rearranged to form: 128 = 2^7
How It Works
The algorithm works by comparing the sorted digits of the input number with the sorted digits of each power of 2. Since we only care about digit rearrangement, sorting both strings allows us to check if they contain the same digits in the same quantities.
For N = 812: sorted digits = "128"
For 128 (which is 2^7): sorted digits = "128"
Since they match, we return True.
Alternative Test Cases
# Test with different numbers
test_cases = [46, 24, 10]
for num in test_cases:
result = solve(num)
print(f"Can {num} be reordered to form a power of 2? {result}")
Can 46 be reordered to form a power of 2? True Can 24 be reordered to form a power of 2? False Can 10 be reordered to form a power of 2? False
Conclusion
This solution efficiently checks if a number's digits can be rearranged to form a power of 2 by comparing sorted digit strings. The time complexity is O(log n) where n is the upper bound, and it handles all possible cases within reasonable limits.
