Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-045

Power of Two

Problem

Return True if the integer n is a power of two and False otherwise, including for n <= 0.

A positive power of two has exactly one set bit, so the expression n & (n - 1) equals zero. Do not use logarithms or loops.

Hint

Subtracting 1 flips the single set bit and all lower bits, so the AND clears everything.

Test cases

case 1
in: [1]
expected: true
case 2
in: [16]
expected: true
case 3
in: [3]
expected: false
case 4
in: [0]
expected: false
case 5
in: [-4]
expected: false
Starter codePython
def is_power_of_two(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor