L1 · FoundationsNumbers & loops~3 min · 6 tests

Check If a Number Is a Power of Two

Test whether n is a power of two in O(1) with the bit trick n & (n - 1) == 0, and compare it with the O(log n) division loop. Python bit manipulation.

The problem

Return True if n is a power of two (1, 2, 4, 8, …). Zero and negative numbers are not.

Examples

  1. Example 1

    Input

    is_power_of_two(16)

    Expected output

    True
  2. Example 2

    Input

    is_power_of_two(18)

    Expected output

    False

+ 4 hidden tests on Submit.

Edge cases to ask about

  • Zero
  • Negative numbers
  • 1 (2⁰)

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · is_power_of_two
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Divide by 2 while evenO(log n)O(1)
    bestn & (n − 1) == 0O(1)O(1)A power of two has exactly one 1-bit; subtracting 1 flips it and everything below.
    Walkthrough of the optimal approach (try it yourself first)

    A power of two in binary is a single 1 followed by zeros (1000). Subtracting 1 turns it into all ones below that bit (0111), so n & (n - 1) is 0 only for powers of two. Guard n > 0 because 0 & -1 is also 0.

    Complexity: O(1) time, O(1) space. A single bitwise AND and comparison.

    Reveal the reference solution
    def is_power_of_two(n):
        return n > 0 and n & (n - 1) == 0

    The brute force, for comparison

    def is_power_of_two(n):
        if n <= 0:
            return False
        while n % 2 == 0:
            n //= 2
        return n == 1

    Follow-ups interviewers ask

    • Count the 1-bits in n.
    • Power of four?

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Check If a Number Is a Power of Two in Python?

    The optimal solution runs in O(1) time and O(1) auxiliary space. A single bitwise AND and comparison.

    What is the brute-force approach, and how do you optimise it?

    Divide by 2 while even: O(log n) time, O(1) space. n & (n − 1) == 0: O(1) time, O(1) space. A power of two has exactly one 1-bit; subtracting 1 flips it and everything below.

    What follow-up questions do interviewers ask about Check If a Number Is a Power of Two?

    Count the 1-bits in n. Power of four?