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?
方法一:
第一次写报错。因为忘记判断n的正负号。
public class Solution {
public boolean isPowerOfFour(int num) {
if(num <= 0)
return false;
while(num != 1){
if (num % 4 != 0)
return false;
num = num /4;
}
return true;
}
}
方法二:
首先判断n&(n-1) 是不是等于0.
如果等于0的话,证明n的二进制中,只含有一个1.也就是说,n是2的倍数。
再其次,判断n的二进制中,这个1的位置。是在奇数位还是偶数位。
0x55555555,实际上是0101,0101,0101,0101,0101,0101,0101,0101
二进制和十六进制是相通的。二进制的四位,相当于16进制的一位。
当n与0x55555555进行与运算之后,如果结果不为0,证明那个唯一的1,不在奇数位,则是正确的。否则,是错误的。
public class Solution {
public boolean isPowerOfFour(int num) {
if ((num & (num-1)) == 0)
{
if((num & 0x55555555) > 0)
return true;
}
return false;
}
}