← Back to Algorithms, page 5

algorithms-0095 · Easy fresher

Bit manipulation basics: get, set, clear and toggle a bit, test for a power of two, count set bits, and find the single number when every other value appears twice.

Use masks: get with (x >> i) & 1, set with x | (1 << i), clear with x & ~(1 << i), toggle with x ^ (1 << i). x & (x - 1) clears the lowest set bit, so x is a power of two when x > 0 and x & (x - 1) == 0, and repeating it counts set bits. XOR of all values cancels pairs and leaves the single number in O(n) time and O(1) space.

Full answer

Problem

Implement the basic bit operations on non-negative integers:

  • get_bit, set_bit, clear_bit, toggle_bit for bit i.
  • is_power_of_two(x), popcount(x) and lowest_set_bit(x).
  • single_number(nums): every value appears exactly twice except one; return it.

Example: for x = 0b1010 (10), bit 1 is 1 and bit 0 is 0; setting bit 0 gives 11; clearing bit 3 gives 2. 64 is a power of two, 12 is not. single_number([4, 1, 2, 1, 2]) is 4.

Constraints: 32-bit values for the classic version; Python integers are unbounded, so negative numbers behave as infinite two's complement.

Brute force

Convert to a binary string and inspect characters: O(bits) per operation with string allocation. For single number, a hash map of counts uses O(n) space.

Optimal approach

  • (x >> i) & 1 reads bit i.
  • x | (1 << i) sets it, x & ~(1 << i) clears it, x ^ (1 << i) flips it.
  • x & (x - 1) removes the lowest set bit. Power of two: x > 0 and x & (x - 1) == 0.
  • Popcount (Kernighan): repeat x &= x - 1 and count steps.
  • Lowest set bit: x & -x.
  • Single number: XOR every value.

Why it works

Subtracting 1 flips the lowest set bit to 0 and all lower zeros to 1, so AND with the original clears exactly that bit. A power of two has a single set bit, so clearing it gives 0. In two's complement, -x is ~x + 1, which keeps the lowest set bit and flips everything above it, so x & -x isolates it. XOR is associative and commutative with a ^ a = 0 and a ^ 0 = a, so paired values cancel in any order.

Complexity

Each mask operation is O(1). Kernighan's popcount is O(number of set bits). Single number is O(n) time and O(1) space. Python 3.10+ also offers int.bit_count().

Code

python
import random


def get_bit(x, i):
    return (x >> i) & 1


def set_bit(x, i):
    return x | (1 << i)


def clear_bit(x, i):
    return x & ~(1 << i)


def toggle_bit(x, i):
    return x ^ (1 << i)


def is_power_of_two(x):
    """A power of two has exactly one set bit; x & (x - 1) clears the lowest set bit."""
    return x > 0 and x & (x - 1) == 0


def popcount(x):
    """Brian Kernighan: loop once per set bit. Non-negative x."""
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n


def lowest_set_bit(x):
    return x & -x


def single_number(nums):
    """Every value appears twice except one. a ^ a = 0 and a ^ 0 = a. O(n), O(1)."""
    out = 0
    for v in nums:
        out ^= v
    return out


if __name__ == "__main__":
    x = 0b1010
    assert get_bit(x, 1) == 1 and get_bit(x, 0) == 0
    assert set_bit(x, 0) == 0b1011 and clear_bit(x, 3) == 0b0010 and toggle_bit(x, 1) == 0b1000
    assert [v for v in range(70) if is_power_of_two(v)] == [1, 2, 4, 8, 16, 32, 64]
    assert lowest_set_bit(12) == 4
    assert single_number([4, 1, 2, 1, 2]) == 4 and single_number([-3, 7, 7]) == -3
    rng = random.Random(95)
    for _ in range(2000):
        v = rng.randint(0, 1 << 40)
        assert popcount(v) == bin(v).count("1")
        assert lowest_set_bit(v) == (0 if v == 0 else 1 << (len(bin(v)) - len(bin(v).rstrip("0"))))
    print("all tests passed")

Save as b95_bit_basics.py and run python3 b95_bit_basics.py. It prints all tests passed (Python 3.13.5).

Edge cases

x = 0 (not a power of two; popcount 0; lowest set bit 0). Negative numbers in Python (use a mask such as & 0xFFFFFFFF to emulate 32-bit). Shifting by 31 or more in fixed-width languages (undefined or sign issues in C and Java). Operator precedence: in Python x & x - 1 already means x & (x - 1), but parentheses make it clear.

Pattern

Masks and XOR cancellation. These building blocks appear in subset enumeration with bitmasks, permission flags, Bloom filters, Gray codes, and DP over subsets.

python
import random


def get_bit(x, i):
    return (x >> i) & 1


def set_bit(x, i):
    return x | (1 << i)


def clear_bit(x, i):
    return x & ~(1 << i)


def toggle_bit(x, i):
    return x ^ (1 << i)


def is_power_of_two(x):
    """A power of two has exactly one set bit; x & (x - 1) clears the lowest set bit."""
    return x > 0 and x & (x - 1) == 0


def popcount(x):
    """Brian Kernighan: loop once per set bit. Non-negative x."""
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n


def lowest_set_bit(x):
    return x & -x


def single_number(nums):
    """Every value appears twice except one. a ^ a = 0 and a ^ 0 = a. O(n), O(1)."""
    out = 0
    for v in nums:
        out ^= v
    return out


if __name__ == "__main__":
    x = 0b1010
    assert get_bit(x, 1) == 1 and get_bit(x, 0) == 0
    assert set_bit(x, 0) == 0b1011 and clear_bit(x, 3) == 0b0010 and toggle_bit(x, 1) == 0b1000
    assert [v for v in range(70) if is_power_of_two(v)] == [1, 2, 4, 8, 16, 32, 64]
    assert lowest_set_bit(12) == 4
    assert single_number([4, 1, 2, 1, 2]) == 4 and single_number([-3, 7, 7]) == -3
    rng = random.Random(95)
    for _ in range(2000):
        v = rng.randint(0, 1 << 40)
        assert popcount(v) == bin(v).count("1")
        assert lowest_set_bit(v) == (0 if v == 0 else 1 << (len(bin(v)) - len(bin(v).rstrip("0"))))
    print("all tests passed")

Mask helpers, Kernighan popcount, lowest set bit and XOR single number, with random checks against bin().count and string-based lowest bit.

Complexity

Time: O(1) per mask operation; O(n) for single number. Space: O(1). Kernighan's loop runs once per set bit; int.bit_count() is a built-in alternative.

By level

Fresher: Writes get, set, clear and toggle with masks and explains each on a 4-bit example. Solves single number with XOR.

Mid: Explains why x & (x - 1) and x & -x work using two's complement and handles 0 and negatives. Extends XOR to the two-singles variant.

Senior: Discusses fixed-width pitfalls across languages, hardware popcount instructions, and bit-packed data structures such as bitsets and Bloom filters. Weighs readability against speed for bit tricks in production code.

Key points

  • Shift and mask to read or write bit i
  • x & (x - 1) clears the lowest set bit
  • Power of two: x > 0 and x & (x - 1) == 0
  • x & -x isolates the lowest set bit
  • XOR cancels pairs

Common mistakes

  • Forgetting x > 0 in the power-of-two test
  • Precedence bugs in languages where & binds looser than ==
  • Ignoring sign behaviour of negative numbers in Python
  • Using a hash map when XOR solves it in O(1) space

Follow-ups

  • How would you swap two variables without a temporary?
  • How do you find two values that each appear once while all others appear twice?
  • How are bit flags used for permissions?

Tips

  • Say each mask out loud with a 4-bit example
  • Mention Python's unbounded integers
  • Explain XOR cancellation with a short list

Evaluation rubric

  • Correct masks
  • Correct power-of-two and popcount
  • XOR solution
  • Edge cases with 0 and negatives