leetcode解题: Power of Four (342)

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?

解法1:log换底

log4(x) == int, 运用log4(x) = log10(x)/log10(4)
C++

1
2
3
4
5
6
7
class Solution {
public:
bool isPowerOfFour(int num) {
double temp = log10(num) / log10(4);
return temp == (int) temp;
}
};

Java

1

解法2:power of two + math

如果是4的次方数,那么-1之后一定能被3整除。
要注意的是&的优先级比==小,所以如果写成num & (num - 1) == 0是不对的。
C++

1
2
3
4
5
6
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0;
}
};