342. Power of Four #2056
-
Topics: Given an integer An integer Example 1:
Example 2:
Example 3:
Constraints:
Follow up: Could you solve it without loops/recursion? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if a given integer Approach
Let's implement this solution in PHP: 342. Power of Four <?php
/**
* @param Integer $n
* @return Boolean
*/
function isPowerOfFour($n) {
if ($n <= 0) {
return false;
}
if (($n & ($n - 1)) != 0) {
return false;
}
$mask = 0x55555555;
return ($n & $mask) != 0;
}
// Test cases
var_dump(isPowerOfFour(16)); // true
var_dump(isPowerOfFour(5)); // false
var_dump(isPowerOfFour(1)); // true
?> Explanation:
This approach efficiently leverages bitwise operations to determine if |
Beta Was this translation helpful? Give feedback.
We need to determine if a given integer
n
is a power of four. An integern
is a power of four if there exists an integerx
such thatn = 4x
. The solution should efficiently check this condition without using loops or recursion.Approach
n
(i.e.,n <= 0
) immediately returnsfalse
.(n & (n - 1)) == 0
. If this condition fails,n
is not a power of two, hence not a power of four.