A2Z Lesson

Log in
← Back to the A2Z sheet

Step 09 Bit Manipulation — Theory

Introduction to Bits and Tricks

Easy

Bit manipulation treats an integer as a row of bits you can inspect and flip directly with AND, OR, XOR, NOT and shifts. It powers some of the most elegant constant-space tricks in all of DSA — finding the one non-repeated element, testing powers of two, counting set bits. This lesson covers the representation, the operators, the i-th bit toolkit, and the handful of classic tricks this module's problems are built from.

Numbers as bits, and two's complement

An integer is stored in binary: 13 is 1101, meaning 8 + 4 + 0 + 1. Bit positions are counted from the right starting at 0, so bit i has value 2^i. A 32-bit int has bits 0..31.

Negative numbers use two's complement: invert all bits and add 1. In 8 bits, -1 is 11111111 and -2 is 11111110. Two consequences worth remembering: the sign lives in the most significant bit, and in fixed-width languages arithmetic wraps around. Python integers have arbitrary precision (conceptually infinitely many sign bits), which removes overflow surprises but means ~x is -x-1 and right-shifting a negative number keeps it negative.

The operators

AND (&) keeps bits set in both operands; OR (|) keeps bits set in either; XOR (^) keeps bits set in exactly one; NOT (~) flips every bit; left shift (<<) moves bits toward higher positions, multiplying by 2 per step; right shift (>>) moves them down, dividing by 2 (floor) per step for non-negative numbers.

XOR deserves special attention because three properties power half the tricks in this module: x ^ x = 0, x ^ 0 = x, and XOR is commutative and associative — order does not matter. That is why XOR-ing a whole array cancels every paired element and leaves the unpaired one.

a, b = 13, 10 # 1101 and 1010 print(a & b) # 1000 = 8 print(a | b) # 1111 = 15 print(a ^ b) # 0111 = 7 print(a << 1) # 11010 = 26 (multiply by 2) print(a >> 1) # 110 = 6 (divide by 2)

The i-th bit toolkit

Everything is done with a mask — a number with a single 1 at position i, written (1 << i).

Check if bit i is set: (n >> i) & 1, or equivalently n & (1 << i) != 0. Set bit i: n | (1 << i). Clear bit i: n & ~(1 << i). Toggle bit i: n ^ (1 << i). Clear the lowest set bit: n & (n - 1) — subtracting 1 flips the lowest 1 to 0 and all bits below it to 1, so the AND wipes exactly that bit. Isolate the lowest set bit: n & (-n).

def check_bit(n, i): return (n >> i) & 1 def set_bit(n, i): return n | (1 << i) def clear_bit(n, i): return n & ~(1 << i) def toggle_bit(n, i): return n ^ (1 << i)

Classic tricks built from the toolkit

Odd or even: n & 1 — the last bit decides. Power of two: a power of two has exactly one set bit, so n > 0 and n & (n - 1) == 0. Count set bits (Brian Kernighan's algorithm): repeatedly clear the lowest set bit and count the steps — O(number of set bits) instead of O(32). Swap without a temp variable: a ^= b; b ^= a; a ^= b. Single non-repeated element: XOR the entire array; pairs annihilate.

Worked micro-example: counting set bits in 13 (1101): 13 & 12 = 12 (1100), count 1; 12 & 11 = 8 (1000), count 2; 8 & 7 = 0, count 3. Three set bits, three iterations.

def count_set_bits(n): count = 0 while n: n = n & (n - 1) # clear lowest set bit count += 1 return count def is_power_of_two(n): return n > 0 and (n & (n - 1)) == 0

Common mistakes

(1) Operator precedence: in many languages == binds tighter than &, so (n & 1) == 1 needs its parentheses — Python included for comparisons against masks. (2) Using 1 << i with i = 31 in 32-bit signed languages overflows into the sign bit; use 1LL in C++ or long masks in Java. (3) Expecting >> on negative numbers to behave like division toward zero — it is an arithmetic shift (floor), and in C++ on negatives it was implementation-defined before C++20. (4) Trying bit tricks on problems that need counts — XOR cancels pairs but cannot tell you how many times something occurred; if elements appear three times (Single Number II), you need per-bit counting modulo 3 instead.

Key points

  • Bit i has value 2^i; a mask (1 << i) is how you address a single bit.
  • Check: (n >> i) & 1. Set: n | mask. Clear: n & ~mask. Toggle: n ^ mask.
  • n & (n - 1) clears the lowest set bit — powers of two and set-bit counting both come from this.
  • XOR properties x^x = 0 and x^0 = x make paired elements cancel — the single-number trick.
  • Watch precedence parentheses, shift widths in fixed-size languages, and negative-number shifts.

Suggested questions

Check if the i-th bit is Set or Not ↗ The mask-and-check operation from the toolkit, on its own.
Check if a Number is Power of 2 or Not ↗ One line once you know the n & (n - 1) trick — plus the n > 0 guard.
Count the Number of Set Bits ↗ Brian Kernighan's loop: clear the lowest set bit until zero.
Swap Two Numbers ↗ The three-XOR swap — a direct drill on XOR properties.
Single Number - I ↗ XOR the whole array; every pair cancels and the single element survives.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.