Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
如果一个数是2的幂次,它的二进制表示里面只有一位1.
如果一个数是4的幂次,同样它的二进制表示里面只有1位1,但是这个1位不能随意出现,4是100,16是10000,也就是隔位出现,把可能出现的位表示成一个数,用这个数去检查是不是4的幂次而排除例如8这样只是2的幂次的数。
public boolean isPowerOfFour(int num) {
return Integer.bitCount(num)==1&&((num&0x55555555)!=0);
}