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?
和前面2和3的情况有些类似,使用了log10,不过好像有点慢
public class Solution {
public boolean isPowerOfFour(int num) {
return (Math.log10(num) / Math.log10(4))%1==0;
}
}
其他方法
public boolean isPowerOfFour(int num) {
return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
//0x55555555 is to get rid of those power of 2 but not power of 4
//so that the single 1 bit always appears at the odd position
}