Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - Implementation

The code

Here's the complete solution:


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

This runs in O(1)O(1) time. The AND operator combines two boolean conditions: positive check and bit pattern check. Both must hold for the result to be true.