Power of Four

342.Power of Four

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

Example 1:

1
2
Input: n = 16
Output: true

Example 2:

1
2
Input: n = 5
Output: false

Example 3:

1
2
Input: n = 1
Output: true

时间复杂度:O(logn)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool isPowerOfFour(int n) {
while(n && n % 4 == 0) {
n /= 4;
}
return n == 1;
}
};

二进制中1的位置:

时间复杂度:O(1)

空间复杂度:O(1)

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

取模性质:

时间复杂度:O(1)

空间复杂度:O(1)

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