The problem is to determine if a given integer can be reordered (by re-arranging its digits) to form a power of 2. In other words, we need to check if any permutation of the number’s digits can form a power of 2.
Example:
To solve this problem, our approach will be:
Generate All Powers of 2: We know that powers of 2 grow exponentially and quickly exceed the limit of (10^9). We will precompute all powers of 2 up to (10^9).
Comparison Using Frequency Counter: For each power of 2 within our computed list, we will compare its frequency of digits (using a counter) with the digit frequency of our given number. If any of them match, it means the number can be rearranged to form that power of 2.
Implementation: Using Python’s collections.Counter
will facilitate the frequency count operations efficiently.
Here is the Python code implementing the strategy:
from collections import Counter
def reorderedPowerOf2(n: int) -> bool:
# Generate powers of 2 up to 2^30, since 2^30 is the largest power of 2 less than 10^9
powers_of_2 = [str(1 << i) for i in range(31)]
# Create a frequency counter for the digits of the given number n
n_counter = Counter(str(n))
# Compare digit frequency of n with each power of 2
for power in powers_of_2:
if n_counter == Counter(power):
return True
return False
# Example Usage
n = 46
print(reorderedPowerOf2(n)) # Output: True (because 46 can be reordered to 64, which is 2^6)
Thus, the overall time complexity is approximately (O(31d) = O(d)), which simplifies to (O(1)) for practical purposes because (d) is bounded and small.
This approach ensures both efficiency and correctness for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?