cswork / templatesOpen the Line 500 list

STOP 35 · DESIGN & BITS

Practical Bit Operations and Numeric Boundaries

Bit tricks and fast power O(log n)

Open the Line 500 list · stop 35 · 14 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 2 companies · in 2 reportsJPMorgan Chase 1, Upstart 1

Warm up with this one

LC 136Single NumberEasy
Stuck? Peek at the approach

Cancel paired elements with XOR and explain its commutative and associative properties.

Key points

  1. x & (x-1) clears the lowest set bit and x & -x isolates it; XOR satisfies a ^ a = 0, which finds the element that appears once.
  2. Fast power splits the exponent into bits: square the base every round and multiply it into the result when the bit is 1, O(log exp).
  3. A set of up to 20 items fits in an integer mask; for (s = mask; s; s = (s-1) & mask) enumerates every non-empty submask.

Common pitfalls

  • Multiplying two values near 10^9 overflows 32 bits; widen to long / long long before the modular multiply.
  • Java's >> keeps the sign, so use >>> for negatives; Python ints are unbounded, so mask negatives with & 0xFFFFFFFF first.
  • In C++ bitwise operators bind looser than comparisons, so x & 1 == 0 means x & (1 == 0); add parentheses (Java refuses to compile it).

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Bits · counting ones with x & (x − 1)

How many 1 bits does 44 have?

Try your own input
x44
02^7
02^6
12^5
02^4
12^3
12^2
02^1
02^0
x−1
·2^7
·2^6
·2^5
·2^4
·2^3
·2^2
·2^1
·2^0
&
·2^7
·2^6
·2^5
·2^4
·2^3
·2^2
·2^1
·2^0
CurrentDiscovered / computedAnswer
x
44
Ones counted
0

x = 44, binary 101100. The rows are x, x − 1 and x & (x − 1). Each round x &= x − 1 clears the lowest 1, so the rounds count the ones.

Invariantx & (x − 1) clears exactly the lowest 1 bit and leaves the rest unchanged.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 136, with it.

Python
def popcount(x: int) -> int:
    """Set bits in a non-negative x (int.bit_count() in Python 3.10+)."""
    count = 0
    while x:
        x &= x - 1  # clear the lowest set bit
        count += 1
    return count


def pow_mod(base: int, exp: int, mod: int) -> int:
    """base ** exp % mod by repeated squaring (the built-in pow(base, exp, mod) does the same)."""
    result, base = 1 % mod, base % mod
    while exp:
        if exp & 1:
            result = result * base % mod
        base = base * base % mod
        exp >>= 1
    return result
C++
// Set bits in x (__builtin_popcount does the same).
int popcount(unsigned x) {
    int count = 0;
    for (; x; x &= x - 1) count++;  // clear the lowest set bit
    return count;
}

// base^exp % mod by repeated squaring; mod < 2^31 keeps every product in 64 bits.
long long powMod(long long base, long long exp, long long mod) {
    long long result = 1 % mod;
    for (base %= mod; exp; exp >>= 1) {
        if (exp & 1) result = result * base % mod;
        base = base * base % mod;
    }
    return result;
}
Java
class Solution {
    // Set bits in x (Integer.bitCount does the same).
    int popcount(int x) {
        int count = 0;
        for (; x != 0; x &= x - 1) count++; // clear the lowest set bit
        return count;
    }

    // base^exp % mod by repeated squaring; mod < 2^31 keeps every product in a long.
    long powMod(long base, long exp, long mod) {
        long result = 1 % mod;
        for (base %= mod; exp > 0; exp >>= 1) {
            if ((exp & 1) == 1) result = result * base % mod;
            base = base * base % mod;
        }
        return result;
    }
}
Go
// popcount counts the set bits in x (bits.OnesCount does the same).
func popcount(x uint) int {
	count := 0
	for ; x != 0; x &= x - 1 { // clear the lowest set bit
		count++
	}
	return count
}

// powMod returns base^exp % mod by repeated squaring; mod < 2^31 keeps every
// product inside an int64.
func powMod(base, exp, mod int) int {
	result := 1 % mod
	for base %= mod; exp > 0; exp >>= 1 {
		if exp&1 == 1 {
			result = result * base % mod
		}
		base = base * base % mod
	}
	return result
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Sieve of Eratosthenes: cross out multiples from i²O(n log log n) time · O(n) space

For every prime up to n (counting them, precomputing smallest prime factors, factorising many numbers): for each prime i, cross out i², i² + i, …; smaller multiples were already crossed out by smaller primes, so start at i², and the outer loop stops at √n. LC 204 (Count Primes); storing the smallest prime factor instead of a boolean factorises any number in O(log n).

Python
def count_primes(n: int) -> int:
    """Number of primes below n (LC 204)."""
    if n < 3:
        return 0
    is_prime = [True] * n
    is_prime[0] = is_prime[1] = False
    i = 2
    while i * i < n:
        if is_prime[i]:
            for j in range(i * i, n, i):  # smaller multiples are already crossed out
                is_prime[j] = False
        i += 1
    return sum(is_prime)
C++
// Number of primes below n (LC 204).
int countPrimes(int n) {
    if (n < 3) return 0;
    vector<bool> isPrime(n, true);
    isPrime[0] = isPrime[1] = false;
    for (long long i = 2; i * i < n; i++)
        if (isPrime[i])
            for (long long j = i * i; j < n; j += i) isPrime[j] = false;  // smaller multiples are already crossed out
    return count(isPrime.begin(), isPrime.end(), true);
}
Java
class Solution {
    // Number of primes below n (LC 204).
    int countPrimes(int n) {
        if (n < 3) return 0;
        boolean[] composite = new boolean[n]; // composite[k]: k has a smaller prime factor
        int count = 0;
        for (long i = 2; i < n; i++) {
            if (composite[(int) i]) continue;
            count++;
            for (long j = i * i; j < n; j += i) composite[(int) j] = true; // smaller multiples are already crossed out
        }
        return count;
    }
}
Go
// countPrimes returns the number of primes below n (LC 204).
func countPrimes(n int) int {
	if n < 3 {
		return 0
	}
	composite := make([]bool, n) // composite[k]: k has a smaller prime factor
	count := 0
	for i := 2; i < n; i++ {
		if composite[i] {
			continue
		}
		count++
		for j := i * i; j < n; j += i { // smaller multiples are already crossed out
			composite[j] = true
		}
	}
	return count
}
XOR to cancel pairs, then split by the lowest differing bitO(n) time · O(1) space

To find the two values that appear once among pairs (LC 260): XOR everything so pairs cancel, leaving a ^ b. Its lowest set bit (x & -x) is a bit where a and b differ, so split all numbers by that bit and XOR each group to get a and b. LC 136 with one single value is a plain XOR; LC 137, with triples, counts each bit mod 3.

Python
def single_numbers(nums: list[int]) -> list[int]:
    """The two values that appear once when every other value appears twice (LC 260), smaller first."""
    xor = 0
    for x in nums:
        xor ^= x  # pairs cancel: xor == a ^ b, nonzero because a != b
    low = xor & -xor  # the lowest bit where a and b differ
    a = b = 0
    for x in nums:
        if x & low:  # that bit splits a and b into different groups; pairs stay together
            a ^= x
        else:
            b ^= x
    return sorted([a, b])
C++
// The two values that appear once when every other value appears twice (LC 260), smaller first.
vector<int> singleNumbers(const vector<int>& nums) {
    unsigned xr = 0;
    for (int x : nums) xr ^= x;  // pairs cancel: xr == a ^ b, nonzero because a != b
    unsigned low = xr & (0u - xr);  // the lowest bit where a and b differ (unsigned: no overflow)
    int a = 0, b = 0;
    for (int x : nums) {
        if (x & low) a ^= x;  // that bit splits a and b into different groups; pairs stay together
        else b ^= x;
    }
    return {min(a, b), max(a, b)};
}
Java
class Solution {
    // The two values that appear once when every other value appears twice (LC 260), smaller first.
    int[] singleNumbers(int[] nums) {
        int xor = 0;
        for (int x : nums) xor ^= x; // pairs cancel: xor == a ^ b, nonzero because a != b
        int low = xor & -xor; // the lowest bit where a and b differ
        int a = 0, b = 0;
        for (int x : nums) {
            if ((x & low) != 0) a ^= x; // that bit splits a and b into different groups; pairs stay together
            else b ^= x;
        }
        return new int[] {Math.min(a, b), Math.max(a, b)};
    }
}
Go
// singleNumbers returns the two values that appear once when every other value appears twice, smaller first.
func singleNumbers(nums []int) []int {
	xor := 0
	for _, x := range nums {
		xor ^= x // pairs cancel: xor == a ^ b, nonzero because a != b
	}
	low := xor & -xor // the lowest bit where a and b differ
	a, b := 0, 0
	for _, x := range nums {
		if x&low != 0 { // that bit splits a and b into different groups; pairs stay together
			a ^= x
		} else {
			b ^= x
		}
	}
	return []int{min(a, b), max(a, b)}
}

Why it works

  1. x & (x − 1) clears the lowest set bit: subtracting 1 turns that bit to 0 and the zeros to its right into ones, so the AND zeroes that stretch and leaves the higher bits alone.
  2. Fast power: write the exponent in binary, e = Σ bᵢ·2ⁱ, so a^e is the product of a^(2ⁱ) over the bits that are 1; squaring the base each round yields the next a^(2ⁱ), for O(log e) rounds.
  3. XOR finds the single number: XOR is commutative and associative with a ^ a = 0 and a ^ 0 = a, so every pair cancels and only the element that appears once remains.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
位运算我常用三个技巧。x & (x − 1) 去掉最低位的 1,可以数 1 的个数或判断 2 的幂;异或满足 a ^ a = 0,成对的数会抵消,用来找只出现一次的数。快速幂把指数拆成二进制,每轮底数平方,遇到 1 的位就乘进结果,O(log n) 次乘法。取模时先转成 64 位再相乘,避免溢出。
English
I lean on three bit tricks. x AND (x − 1) clears the lowest set bit, which counts set bits or tests for a power of two, and XOR cancels pairs because a XOR a is zero, which finds the element that appears once. Fast power splits the exponent into bits, squaring the base each round and multiplying it in when the bit is one, for O(log n) multiplications. Under a modulus I widen to 64 bits before multiplying.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. For a positive integer x, what does x & (x - 1) == 0 mean?
  2. What is the bitwise XOR of all of [7, 3, 5, 3, 7]?
  3. In two's complement, what does x & -x give? Take x = 12.
  4. x is a non-negative integer. How many times does the loop run?
    def ones(x):
        count = 0
        while x:
            x &= x - 1
            count += 1
        return count
  5. a and b are positive; treat one modulo as O(1). What is the time complexity?
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

def popcount(x: int) -> int:
    """Set bits in a non-negative x (int.bit_count() in Python 3.10+)."""
    count = 0
    return result

Practice by stage

This stop's 14 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 5

#ProblemApproachRating
136Single NumberCancel paired elements with XOR and explain its commutative and associative properties.
191Number of 1 BitsCount set bits by clearing the lowest set bit, making unsigned fixed-width semantics explicit.
338Counting BitsReuse bit counts of smaller integers and compare per-number scanning with a linear recurrence.
231Power of TwoCheck whether exactly one bit is set, handling zero and negative numbers separately.
9Palindrome NumberReverse only half the digits to check a palindrome, handling negatives, trailing zeros, and the middle digit of odd-length numbers.

Core 7

#ProblemApproachRating
190Reverse BitsReconstruct the result across exactly 32 bits without losing width because of leading zeros.
137Single Number IIRecover the uniquely occurring value through per-bit counts modulo the repetition count, handling negative two's-complement results.
260Single Number IIIPartition by a set bit in the XOR difference and prove that each group leaves exactly one unique element.
201Bitwise AND of Numbers RangeReduce bitwise AND over a consecutive interval to its common binary prefix instead of enumerating a large range.
69Sqrt(x)Find the floor square root using integer boundaries and division-based comparisons to avoid multiplication overflow.
172Factorial Trailing ZeroesCount factors by powers of five instead of computing a huge factorial, including repeated factors.
204Count PrimesUse a sieve to eliminate composites in bulk, explaining why marking starts at the square and why the upper bound is strictly below n.

Advanced 2

#ProblemApproachRating
371Sum of Two IntegersSeparate the sum without carries from the carries and handle fixed-width masking under Python's arbitrary-precision integers.
166Fraction to Recurring DecimalSimulate long division and record each remainder's first position to locate the repeating cycle, handling signs and exact division.