- Reordered Power of 2
Medium
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: 16
Output: true
Example 4:
Input: 24
Output: false
Example 5:
Input: 46
Output: true
Note:
1 <= N <= 10^9
思路
HashMap~~
代码
class Solution {
public boolean reorderedPowerOf2(int N) {
long c = hash(N);
for (int i = 0; i < 32; i++)
if (hash(1 << i) == c) return true;
return false;
}
//类似于Hash的思想,计数某个数字出现的次数和构成的hash值
//比较2^0---2^31跟这个数构成的hash值
//9 8 7 6 5 4 3 2 1 0
//对应出现次数
//如何比较计数表和2^n的计数表?
//计数表转化为9位数
public long counter(int N) {
long res = 0;
for (; N > 0; N /= 10) res += (int)Math.pow(10, N % 10);
return res;
}
public long hash(int N){
long res = 0;
int [] key = new int[] {2,3,5,7,9,11,13,17,19,23};
for(; N > 0; N/=10)
res += key[N%10] * (N%10);
return res;
}
}