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.
分析:
和判断一个数是否为3的幂类似,可以用循环/4判断余数或者利用对数来判断,代码如下:
解法1:
class Solution {
public:
bool isPowerOfFour(int num) {
if(num <= 0)
return false;
if(num == 1)
return true;
while(num/4 != 1)
{
if(num%4 != 0)
return false;
else
num /= 4;
}
if(num % 4 == 0)
return true;
else
return false;
}
};
解法2:
class Solution {
public:
bool isPowerOfThree(int num) {
if(num <= 0)
return false;
if(int(log10(num)/log10(4)) - log10(num)/log10(4) == 0)
return true;
else
return false;
}
};