A positive power of two has exactly one bit set: 1, 2, 4, 8, 16, and so on.
That single-bit property gives a beautiful test. If n is a power of two, then n - 1 flips that one bit off and turns every lower bit on, so n & (n - 1) is 0. Watch out for 0 and negatives, which are not powers of two.
Implement is_power_of_two(n) to return True when n is a positive power of two, else False.
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
def is_power_of_two(n):
"""Return True if n is a positive power of two, else False.
A power of two has exactly one set bit, so n & (n - 1) == 0.
"""
# TODO: return True only when n is positive AND (n & (n - 1)) == 0.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
A positive power of two has exactly one bit set: 1, 2, 4, 8, 16, and so on.
That single-bit property gives a beautiful test. If n is a power of two, then n - 1 flips that one bit off and turns every lower bit on, so n & (n - 1) is 0. Watch out for 0 and negatives, which are not powers of two.
Implement is_power_of_two(n) to return True when n is a positive power of two, else False.
Press Run Tests or ββ© to check your solution.