Single-Bit Operations

Step 4: Single-Bit Operations

Flags and bitsets need four core operations on bit i of an integer n, all built from a shifted mask 1 << i:

  • get_bit(n, i) returns the bit (0 or 1) via (n >> i) & 1
  • set_bit(n, i) forces the bit to 1 via n | (1 << i)
  • clear_bit(n, i) forces the bit to 0 via n & ~(1 << i)
  • toggle_bit(n, i) flips the bit via n ^ (1 << i)

Implement all four functions.

Hints
Starter code
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
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.