题目
Starting with a positive 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 in a way such that the resulting number is a power of 2.
Example 1:
Input: 1
Output: true
Example 2:
Input: 10
Output: false
Example 3:
Input: 61
Output: true
Note:
1 <= N <= 10^9
思路
判断一个数 N
是否存在这样的排列(开始的位不能为0)为2的幂数可以利用 N
所拥有的1~9的数量与相同位数的2的幂数拥有的 0~9
的数量来进行比较。
即比如 1289
,拥有的 0~9
的数量分别为: [0,1,1,0,0,0,0,0,1,9]
;
相同位数的2的幂数有:1024,2048,4096,8192
.很容易得到 1289
和 8192
拥有的数量相同。
Code in C++
(代码较长,可以更精简)
class Solution {
public:
bool reorderedPowerOf2(int N) {
if (N < 1)
return false;
vector<int> digits(10);
int digitNum = 0, bound = 1;
while (N) {
digits[N%10]++;
++digitNum;
N /= 10;
bound *= 10;
}
int target = 1;
while (target < bound/10) {
target <<= 1;
}
bool ifMatch = true;
while (target < bound) {
int tmp = target;
vector<int> tmpDigits(10);
while (tmp) {
tmpDigits[tmp%10]++;
tmp /= 10;
}
for (int i = 0; i < 10; ++i) {
if (tmpDigits[i] != digits[i]) {
ifMatch = false;
break;
}
}
if (ifMatch)
return true;
ifMatch = true;
target <<= 1;
}
return false;
}
};
性能
优化方案
- 2的幂数不多,
<10^9
的幂数只有30个,可以提前计算好,作为静态数组直接调用。 - 观察每个2的幂数,可以发现每个幂数拥有的同一个数字的数量都没超过4个,可以把
0~9
的数量用2bit,或者更保险一点用3bit来存储,只需要30bit(<sizeof(uint32_t)
)。这样只需要比较一个32位的整数是否相等即可。