869. Reordered Power of 2
Description
You are given an integer n
. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true
if and only if we can do this so that the resulting number is a power of two.
Example 1:
Input: n = 1 Output: true
Example 2:
Input: n = 10 Output: false
Constraints:
1 <= n <= 109
Solutions
Solution 1: Enumeration
We can enumerate all powers of 2 in the range \([1, 10^9]\) and check if their digit composition is the same as the given number.
Define a function \(f(x)\) that represents the digit composition of number \(x\). We can convert the number \(x\) into an array of length 10, or a string sorted by digit size.
First, we calculate the digit composition of the given number \(n\) as \(\text{target} = f(n)\). Then, we enumerate \(i\) starting from 1, shifting \(i\) left by one bit each time (equivalent to multiplying by 2), until \(i\) exceeds \(10^9\). For each \(i\), we calculate its digit composition and compare it with \(\text{target}\). If they are the same, we return \(\text{true}\); if the enumeration ends without finding the same digit composition, we return \(\text{false}\).
Time complexity \(O(\log^2 M)\), space complexity \(O(\log M)\). Where \(M\) is the upper limit of the input range \({10}^9\) for this problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|