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 . This works because powers of 2 have exactly one bit set. Time: . Space: .