Difficulty: Easy
Related Topics: Bit Manipulation
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 == 4<sup>x</sup>.
Example 1:
Input: n = 16Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
-2 <= n <= 2 - 1
Follow up: Could you solve it without loops/recursion?
Solution
Language: Java
class Solution {
/*
解题思路:
1. 先判断是不是2的次方数 (n & n - 1) == 0
2. 在判断它是不是4的次方数
*/
public boolean isPowerOfFour(int n) {
if (n <= 0) return false;
int mask = 0x55555555;
/*
01010101
& 00010000
----------
00010000 <- not equal 0
*/
return (n & n - 1) == 0 && (n & mask) != 0;
}
}
