LeetCode-342. Power of Fourhttps://leetcode.com/problems/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:
Input: n = 16 Output: true
Example 2:
Input: n = 5 Output: false
Example 3:
Input: n = 1 Output: true
Constraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
解题思路
是不是2 的(整数)次方:如果一个数字n 是2 的整数次方,那么它的二进制一定是0...010...0 这样的形式;考虑到n- 1 的二进制是0...001...1,这两个数求按位与的结果一定是0。因此如果n & (n - 1) 为0,那么这个数是2 的次方。
如果这个数也是4 的次方,那二进制表示中1 的位置必须为奇数位。我们可以把n 和二进制
的10101...101(即十进制下的1431655765)做按位与,如果结果不为0,那么说明这个数是4 的
次方。
【C++】
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0b01010101010101010101010101010101) != 0;
}
};
【Java】
class Solution {
public boolean isPowerOfFour(int n) {
return n > 0 && ((n & (n - 1)) == 0) && ((n & 1431655765) > 0);
}
}