easy +8 pts

Check Power of Two Bits

Determine if a number is a power of two using bitwise operations.

Write a function `is_power_of_two(n: int) -> bool` that returns `True` if the given integer `n` is a power of two (i.e., 1, 2, 4, 8, ...), and `False` otherwise. Use bitwise operations to solve the problem. The condition `(n > 0) and (n & (n - 1)) == 0` is the standard trick: a power of two has exactly one bit set, and `n & (n - 1)` removes the lowest set bit. If the result is 0, the number was a power of two. Edge cases: `n` can be negative, zero, or a large positive integer. Negative numbers and zero are never powers of two.

Constraints

Input is an integer `n`. The function should handle values in the range of Python's arbitrary-precision integers. Time complexity should be O(1) (constant number of operations).

Example

>>> is_power_of_two(1)
True
>>> is_power_of_two(16)
True
>>> is_power_of_two(18)
False
>>> is_power_of_two(0)
False
>>> is_power_of_two(-8)
False
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

What does the binary representation of a power of two look like?
What happens when you perform n & (n - 1) on a power of two?
Don't forget to handle non-positive numbers before applying the bitwise trick.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.