public boolean isPowerOf2(int n) {
// ex let say 32 => 10000 & (10000 - 1 = 1111) => 000000 true
// 31 => 1111 & (1111 - 1 = 1110) => 1110 false
return x != 0 && (x & (x - 1) == 0);
}
class Solution {
public boolean reorderedPowerOf2(int N) {
int[] A = count(N);
// 2^31 = 1073741824 > 10^9 = 1000000000
for (int i = 0; i < 30; ++i)
if (Arrays.equals(A, count(1 << i)))
return true;
return false;
}
// Returns the count of digits of N
// Eg. N = 112223334, returns [0,2,3,3,1,0,0,0,0,0]
public int[] count(int N) {
int[] ans = new int[10];
while (N > 0) {
ans[N % 10]++;
N /= 10;
}
return ans;
}
}
Time: O(log^2N), count(1 << i) logN, equals LogN
Space: O(Log^N), why? there are 30 arrays for power of 2s < 10000000000