Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - Implementation

The code

Here's the complete solution:


function isPowerOfTwo(n)
    if n  0 then
        return false
    return (n & (n - 1)) = 0

First, handle the edge case: non-positive numbers cannot be powers of 2. Then check if n&(n1)=0n \& (n-1) = 0. This works because powers of 2 have exactly one bit set. Time: O(1)O(1). Space: O(1)O(1).