[leetcode]869. Reordered Power of 2
Analysis
等国庆等国庆!!!!!—— [每天刷题并不难]
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.
先统计出N中各个数字的个数,然后再统计出2的0次方到2的31次方的的各个位置的数字的个数,如果N的统计结果跟这32个数字的某一个统计结果相同,那么就返回true。比如 1042中1、0、2、4的出现次数都为1,然后2的十次方的统计结果中也是这样,那么1042的某个组合就是2的10次方,就返回true。这里判断出现次数的时候不要用数组记录,因为判断两个数组是否相等会比较麻烦,我用数组判断的时候提交总是有奇怪的bug,然后在大神那里看到了一个方法:把每个数字设为10的多少次方,这样就没必要去比较整个数组是否相等,直接把这组数字用10的多少次方表示出来;比如N=4654,其中有2个4,1个5,1个6,因此可以表示为:10{4}+10{4}+10{5}+10{6},这样出来的结果是唯一的,然后再进行比较。
Implement
class Solution {
public:
bool reorderedPowerOf2(int N) {
double cnt0 = 0;
while(N){
int tmp = N%10;
cnt0 += pow(10, tmp);
N /= 10;
}
for(int i=0; i<32; i++){
int num = 1<<i;
double cnt1 = 0;
while(num){
int tmp = num%10;
cnt1 += pow(10, tmp);
num /= 10;
}
if(cnt0 == cnt1)
return true;
}
return false;
}
};