The Single Bit

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Capital One

Problem

Given an integer, return True if it is a positive power of 2 (1, 2, 4, 8, 16, ...). Use bitwise operations: (n > 0) AND (n & (n - 1)) == 0.

One particular pattern hides in plain sight.

Example 1

Input:

n = 16

Output:

true

Example 2

Input:

n = 6

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This tests bitwise operations and understanding of binary representation. Powers of two have exactly one bit set, and the classic n & (n - 1) trick clears the lowest set bit, making it a single-operation check.


Break down the requirements

Step 1: Guard against non-positive inputs

Zero and negative numbers are not powers of two. Check n > 0 first.

Step 2: Apply the bit trick

Compute n & (n - 1). If the result is 0, n has exactly one bit set and is a power of two.


The solution

Single-bit check with AND trick
def is_power_of_two(n: int) -> bool:
    if n <= 0:
        return False
    result = (n & (n - 1)) == 0
    return result

Common follow-up questions