问题描述:
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?
首先直观解法:bool isPowerOfFour(int num)
{
if(num <= 0)
return false;
while(num && (num % 4 == 0))
{
num = num / 4;
}
return (num == 1);
}
其次分析规律,4的次幂,
1(1)、4(100)、16(10000)······
二进制表示中只有一位为1,并且只最高位,并且为奇数位。
依据2的次幂的解法,就是多了一个最高位为奇数位的判断,与 0x55555555相与就行了。
bool isPowerOfFour(int num)
{
if(num <= 0)
return false;
if( !(num & (num-1)))
{
if(num & 0x55555555)
return true;
}
return false;
}