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^k ) where ( k ) is a non-negative integer.
true
if ( n ) is a power of two, otherwise return false
.To determine if ( n ) is a power of two, we can utilize the properties of binary representation of powers of two:
A power of two in binary form has exactly one ‘1’ bit and the rest are ‘0’s. For example, 1 (2^0), 2 (2^1), 4 (2^2), 8 (2^3) are 1, 10, 100, and 1000 in binary respectively.
One efficient way to leverage this property is using a bitwise AND operation. For a binary number that represents a power of two:
Additionally, ( n ) should be greater than 0.
public class Solution {
public boolean isPowerOfTwo(int n) {
// If n is less than or equal to 0, it can't be a power of two
if (n <= 0) {
return false;
}
// Check if n is a power of two using the bitwise trick
return (n & (n - 1)) == 0;
}
}
false
because a power of two must be a positive number.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?