2021.10.28 force deduction - one question per day - reorder to get a power of 2

It's too powerful 2022-01-15 01:39:27

Title Description :

Given a positive integer N , We do it in any order ( Including the original sequence ) Reorder numbers , Note that the leading number cannot be zero .

If we can get  2 The power of , return true; otherwise , return false.

Method 1 :

class Solution {
public:
bool reorderedPowerOf2(int n) {
string str;
stringstream ss;
ss << n;
ss >> str;
int len = str.size();
int vec1[10] = { 0 };
// Calculation n How many numbers are there in
for (int i = 0; i < len; i++)
{
vec1[str[i] - '0']++;
}
//x and n Same number of digits ,y Than n Big one digit
int x = 1;
for (int i = 0; i < len - 1; i++)
{
x *= 10;
}
int y = x * 10;
int num = 1;
while (num < x)
{
num *= 2;
}
// At greater than or equal to x, Less than or equal to y Of 2 In the power of , Find the number of numbers equal to and n same , This explanation n Can be arranged into num
while (num >= x && num < y)
{
string curstr;
int vec2[10] = { 0 };
stringstream curss;
curss << num;
curss >> curstr;
for (int i = 0; i < curstr.size(); i++)
{
vec2[curstr[i] - '0']++;
}
bool flag = true;
for (int i = 0; i < 10; i++)
{
if (vec1[i] != vec2[i])
{
flag = false;
break;
}
}
if (flag) return true;
num *= 2;
}
return false;
}
};

Considering the exponential explosion , So if you judge one by one 2 Whether the power of can satisfy the meaning of the question , Then it won't take much time , Moreover , got it n After a few digits , Just judge 2 Those numbers with equal digits in the power of .


thank
Similar articles
***

2022-01-15

***

2022-01-15

***

2022-01-15

2022-01-15

2022-01-15

2022-01-15

2022-01-15

2022-01-15