问题描述:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
示例:
Given num = 16, return true. Given num = 5, return false.
问题分析:
一个数若是4的幂,那么它一定是2的幂,而且转换成二进制时,1总是在奇数位上,而且对于任意4的幂减去1后都能被三整除。
因而有两种解决方案:
class Solution {
public:
bool isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
}
};
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
};