Flags and bitsets need four core operations on bit i of an integer n, all built from a shifted mask 1 << i:
Implement all four functions.
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
def single_number(nums):
result = 0
for x in nums:
result ^= x
return result
def get_bit(n, i):
"""Return bit i of n as 0 or 1."""
# TODO: shift n right by i, then mask with 1.
pass
def set_bit(n, i):
"""Return n with bit i forced to 1."""
# TODO: OR n with (1 << i).
pass
def clear_bit(n, i):
"""Return n with bit i forced to 0."""
# TODO: AND n with the inverse mask ~(1 << i).
pass
def toggle_bit(n, i):
"""Return n with bit i flipped."""
# TODO: XOR n with (1 << i).
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Flags and bitsets need four core operations on bit i of an integer n, all built from a shifted mask 1 << i:
Implement all four functions.
Press Run Tests or ββ© to check your solution.