Python 3D Academyবাংলা

Bit tricks: the single number, powers of two, counting bits

🌍 In real life. At an office gate every worker taps their ID card when they come in and again when they leave. At night the guard has a long list of IDs, and every ID appears twice, except one: someone is still inside. Sorting the list or counting each ID works, but one pass with XOR finds the missing tap using no extra memory at all.

The idea in one sentence: a few facts about switches give fast answers: x ^ x is 0 and x ^ 0 is x, so XOR cancels pairs; and n & (n − 1) clears the lowest switch that is on, which counts the 1s and spots powers of two.

Its words:

  • cancel: XOR the same number twice and it vanishes, in any order
  • lowest set bit: the rightmost switch that is on
  • power of two: 1, 2, 4, 8, …: exactly one switch on
  • popcount: how many switches are on

Finding the single number, step by step:

  1. start with 0
  2. XOR in every number, in any order
  3. the pairs cancel, so what is left is the single number

Watch the pairs cancel in 4, 1, 2, 1, 2:

Clearing the lowest switch. Subtracting 1 turns the lowest on switch off and every switch below it on (44 = 101100, 43 = 101011). AND keeps only what both share, so n & (n − 1) is n without its lowest switch. Count how many times you can do it before n is 0:

Why it works. XOR is place by place, and in each place a pair of equal bits gives 0; the order doesn't matter because XOR, like addition, can be regrouped freely. A power of two has exactly one switch on, so clearing it leaves 0: n & (n − 1) == 0 means n is a power of two, as long as n > 0.

What it costs, by counting. XOR over 1,000,000 card taps is 1,000,000 steps, O(n) time and O(1) memory; a dict of counts is also O(n) time but stores up to 500,000 IDs. Counting the 1s this way loops once per switch that is on, at most 8 times for a number below 256.

def single_number(nums):
    acc = 0
    for x in nums:
        acc ^= x          # a pair cancels: x ^ x == 0, and x ^ 0 == x
    return acc

def count_bits(n):
    count = 0
    while n:
        n &= n - 1        # clears the lowest switch that is on
        count += 1
    return count

def is_power_of_two(n):
    return n > 0 and n & (n - 1) == 0   # exactly one switch on

print(single_number([4, 1, 2, 1, 2]))
print(count_bits(44), bin(44).count("1"))
print([n for n in range(20) if is_power_of_two(n)])

Mistakes and edge cases.

  • zero is not a power of two: 0 & -1 is 0 too, so check n > 0 first
  • only pairs cancel: XOR finds the single number only when every other number appears an even number of times
  • XOR is not subtraction: 5 ^ 3 is 6, not 2
  • counting with len(bin(n)): that counts every switch, on or off; count the 1s instead

Quiz

  1. What does this print?

    print(5 ^ 5, 5 ^ 0, 7 ^ 2 ^ 7)
  2. What does this print?

    def count_bits(n):
        count = 0
        while n:
            n &= n - 1        # clears the lowest switch that is on
            count += 1
        return count
    
    print(count_bits(7), count_bits(64))
  3. What is 12 & 11?

    • 8: 12 without its lowest on switch
    • 11
    • 0
  4. Why does XOR find the single number in any order?

    • XOR can be regrouped and reordered freely, so each pair meets and cancels
    • The list must be sorted first
    • XOR keeps the biggest number
  5. is_power_of_two(0) answers True. Which line is wrong?

    def is_power_of_two(n):
        return n & (n - 1) == 0

Coding tasks

  1. Write single_number(nums): every number in nums appears twice except one, which appears once. Return that one, in O(n) time and O(1) extra memory.

  2. Write count_bits(n): how many switches of the whole number n are on.

  3. Write is_power_of_two(n): True if the whole number n is 1, 2, 4, 8, …, else False.