原题网址:342. Power of Four 342. Power of Four 342. Power of Four 342. Power of Four
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?
方法:判断是否只有个1个比特为1,并且1后面有偶数个0。
public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & -num) == num && (num & 0x55555555) != 0;
}
}
另一种实现:
public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & -num) == num && (num & 0x2AAAAAAA) == 0;
}
}