题目
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
答案
class Solution {
public boolean isPowerOfFour(int num) {
// Power of 4 <=>
// (1) number of trailing 0's in binary reprensentation is even <=>
// Binary representation has only one 1 and it's in odd position
// Need to check the above two conditions
// First, check all 1's in binary representation of num are in odd position
boolean odd = (num | 0x55555555) == 0x55555555;
// Second, check binary representation of num has only one 1(Equivalent to num is a power of 2)
boolean one = num != 0 && (num & (num - 1)) == 0;
return odd && one;
}
}