思路一:直接全排列模拟,这里不用将所有全排列结果存下来,而是一边递归,一边判断。
思路二: 打表+枚举。只要位数符合,一定可以构造出来。
这里有个技巧,我们可以用string,或者python中的tuple来表示cnt,或者位运算来表示cnt。
这样就很容易判断出n的cnt是否和二进制表的cnt相同。
def countDigits(n: int) -> Tuple[int]:
cnt = [0] * 10
while n:
cnt[n % 10] += 1
n //= 10
return tuple(cnt)
powerOf2Digits = {countDigits(1 << i) for i in range(30)}
class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
return countDigits(n) in powerOf2Digits
优雅的C++写法
string countDigits(int n) {
string cnt(10, 0);
while (n) {
++cnt[n % 10];
n /= 10;
}
return cnt;
}
unordered_set<string> powerOf2Digits;
int init = []() {
for (int n = 1; n <= 1e9; n <<= 1) {
powerOf2Digits.insert(countDigits(n));
}
return 0;
}();
class Solution {
public:
bool reorderedPowerOf2(int n) {
return powerOf2Digits.count(countDigits(n));
}
};