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 = = 4 x n == 4^x 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 -2^{31} <= n <= 2^{31} - 1 −231<=n<=231−1
From: LeetCode
Link: 342. Power of Four
Solution:
Ideas:
- n > 0: Ensures the number is positive.
- (n & (n - 1)) == 0: This checks if n is a power of two.
- (n & 0x55555555) != 0: This checks that the single bit set in n is in an odd position, confirming that n is a power of four.
Code:
c
bool isPowerOfFour(int n) {
// Check if n is positive and a power of two
if (n > 0 && (n & (n - 1)) == 0) {
// Check if the single set bit is in an odd position
return (n & 0x55555555) != 0;
}
return false;
}