231. Power of Two #2031
-
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 ApproachThe approach leverages bit manipulation properties of numbers that are powers of two. Here's the key insight:
Thus, the solution involves:
Let's implement this solution in PHP: 231. Power of Two <?php
/**
* @param Integer $n
* @return Boolean
*/
function isPowerOfTwo($n) {
if ($n <= 0) {
return false;
}
return ($n & ($n - 1)) === 0;
}
// Test cases
var_dump(isPowerOfTwo(1)); // true (2^0)
var_dump(isPowerOfTwo(16)); // true (2^4)
var_dump(isPowerOfTwo(3)); // false
var_dump(isPowerOfTwo(0)); // false
var_dump(isPowerOfTwo(-2)); // false
?> Explanation:
This approach efficiently checks the power of two condition in constant time O(1) using bitwise operations, avoiding the need for loops or recursion. The solution handles all edge cases, including zero and negative numbers, as well as the entire range of 32-bit integers. |
Beta Was this translation helpful? Give feedback.
We need to determine if a given integer
n
is a power of two. A number is considered a power of two if it can be expressed as 2^x where x is a non-negative integer. The solution should efficiently check this condition without using loops or recursion.Approach
The approach leverages bit manipulation properties of numbers that are powers of two. Here's the key insight:
false
for these cases.1
in binary.10
in binary.100
in …