題目:
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.
解析:
使用二進(jìn)制來考慮問題。
因?yàn)槭?2位有符號(hào)數(shù),所以先保證num > 0。一個(gè)數(shù)是4的冪必然是2的冪,先來看看2的冪的特征(num & (num - 1)) == 0
比如數(shù)字8:(8 & 7) --> (0x1000 & 0x0111)。所有是2的冪的數(shù)n都滿足二進(jìn)制位只有一個(gè)1,后面都是0。(n-1)滿足全為1。
再在2的冪中篩選去掉不是4的冪的。
4的冪的二進(jìn)制中1總是出現(xiàn)在奇數(shù)位,比如:4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000)
其他則是在偶數(shù)位,比如 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)
所以要滿足(num & 0x55555555) != 0
,這里0x55555555
(0b 0101 0101 0101 0101 0101 0101 0101 0101
)正是32位有符號(hào)整數(shù)。
答案一:
class Solution {
public:
bool isPowerOfFour(int num) {
return ((num > 0)
&& ((num & (num - 1)) == 0)
&& ((num & 0x55555555) == num) );
}
};
答案二(基礎(chǔ)解法):
class Solution {
public:
bool isPowerOfFour(int num) {
if (num == 1) {
return true;
}
if (num == 0) {
return false;
}
while ( (num % 4 == 0)) {
num /= 4;
if (num == 1) {
return true;
}
}
return false;
}
};