1. 题目来源
链接:342. 4的幂
前导题:[E位运算] lc231. 2 的幂(位运算+lowbit操作)
2. 题目解析
是 4^x
的话一定也是 2^x
,且 4^x=2^2x
,我们可以判断 n
是否是一个完全平方数,再判断其是否为 2^x
即可。注意在使用 sqrt()
过程中针对 INT_MIN
开方后,再相乘的话会爆 INT_MIN
。
class Solution {
public:
bool isPowerOfFour(int n) {
if (n <= 0) return false;
int t = sqrt(n);
if (t * t != n) return false;
return (n & -n) == n;
}
};
时间复杂度:
O
(
l
o
g
n
)
O(logn)
O(logn),取决于 sqrt()
的时间复杂度,可以将其看为
O
(
1
)
O(1)
O(1) 的。
空间复杂度: O ( 1 ) O(1) O(1)
很明显,如果是 4^x
一定是 2^x
且一定只有偶数位上的 1,即只有 2^0,2^2,2^4....
仅需判断 2^x
中的那一位 1 是否在偶数位置上出现即可。
构造: m a s k = ( 10101010101010101010101010101010 ) 2 mask=(10101010101010101010101010101010)_2 mask=(10101010101010101010101010101010)2
class Solution {
public:
bool isPowerOfFour(int n) {
return n > 0 && (n & -n) == n && (n & 0xaaaaaaaa) == 0;
}
};
时间复杂度: O ( 1 ) O(1) O(1)
空间复杂度: O ( 1 ) O(1) O(1)