class Solution {
public:
bool reorderedPowerOf2(int n) {
vector a;
while(n>0)
{
int x=n%10;
a.push_back(x);
n=n/10;
}
sort(a.begin(),a.end());
for(int i=0;i<30;i++)
{
vector b;
int c=pow(2,i);
while(c>0)
{
int x=c%10;
b.push_back(x);
c=c/10;
}
sort(b.begin(),b.end());
if(a==b)
{
return 1;
}
}
return 0;
}
};
做出来了但结果并不是很好。
class Solution {
vector vis;
bool isPowerOfTwo(int n) {
return (n & (n - 1)) == 0;
}
bool backtrack(string &nums, int idx, int num) {
if (idx == nums.length()) {
return isPowerOfTwo(num);
}
for (int i = 0; i < nums.length(); ++i) {
// 不能有前导零
if ((num == 0 && nums[i] == '0') || vis[i] || (i > 0 && !vis[i - 1] && nums[i] == nums[i - 1])) {
continue;
}
vis[i] = 1;
if (backtrack(nums, idx + 1, num * 10 + nums[i] - '0')) {
return true;
}
vis[i] = 0;
}
return false;
}
public:
bool reorderedPowerOf2(int n) {
string nums = to_string(n);
sort(nums.begin(), nums.end());
vis.resize(nums.length());
return backtrack(nums, 0, 0);
}
};
这是答案,用了搜索回溯 + 位运算;
递归迟早要拿下。
原本我也想用字符串,不过不清楚怎么转字符串:
string nums = to_string(n);
其中还有如何判断二的幂的位与运算:
return (n & (n - 1)) == 0;
加油!



