Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - Implementation

One-line check

Here is the complete solution:


function isPowerOfTwo(n)
    return n > 0 and (n & (n - 1)) = 0

The check n>0n > 0 excludes zero and negative numbers. The expression n&(n1)=0n \& (n - 1) = 0 ensures exactly one 1 bit. Time: O(1)O(1). Space: O(1)O(1). This bit trick replaces a loop with a single operation.