To solve this problem, we need to determine if a given number is a power of two. A number is a power of two if it has exactly one '1' bit in its binary representation and is a positive integer.
Approach
The key insight here is leveraging bitwise operations to efficiently check for the presence of exactly one '1' bit:
- Positive Check: Powers of two are always positive, so any number ≤ 0 can immediately be ruled out.
- Bitwise AND with (n-1): For a number ( n ) that is a power of two, ( n ) in binary form is a 1 followed by zeros (e.g., 2=10,4=100,8=1000). Subtracting 1 from ( n ) flips all bits after the single '1' bit (e.g., 2-1=1=01,4-1=3=011,8-1=7=0111). The bitwise AND of ( n ) and ( n-1 ) will be 0 if and only if ( n ) is a power of two.
Solution Code
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
Explanation
Let’s break down the solution:
- Positive Check: ( n > 0 ) ensures we only consider positive numbers (since powers of two are positive).
- Bitwise AND: ( n & (n-1) ===0 ) checks if there is exactly one '1' bit in the binary representation of ( n ). For example:
- ( n=8 ) (binary:1000), ( n-1=7 ) (binary:0111), ( 8&7=0 ) → true.
- ( n=6 ) (binary:110), ( n-1=5 ) (binary:101), (6&5=100≠0 ) → false.
- (n=1) (binary:1), (n-1=0) (binary:0), (1&0=0) → true (since (1=2^0)).
This approach is O(1) time complexity (constant time) because it involves a fixed number of bitwise operations, making it very efficient even for large numbers. It also avoids floating-point inaccuracies that can occur with logarithmic methods.
Edge Cases:
- (n=0): Returns false (not a power of two).
- (n=-2): Returns false (negative numbers are not powers of two).
- (n=1): Returns true (valid, as (1=2^0)).
This solution handles all edge cases correctly and efficiently. ✅

作者声明:本文包含人工智能生成内容。