STOP 35 · DESIGN & BITS
Practical Bit Operations and Numeric Boundaries
Bit tricks and fast power O(log n)
- 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 NumberStuck? Peek at the approach
Cancel paired elements with XOR and explain its commutative and associative properties.
Key points
- 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.
- 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).
- 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.
Bits · counting ones with x & (x − 1)
How many 1 bits does 44 have?
Try your own input
- 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 resultC++
// 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
- 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.
- 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.
- 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 位再相乘,避免溢出。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.
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
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 resultPractice 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
| # | Problem | Approach | Rating |
|---|---|---|---|
| 136 | Single Number | Cancel paired elements with XOR and explain its commutative and associative properties. | |
| 191 | Number of 1 Bits | Count set bits by clearing the lowest set bit, making unsigned fixed-width semantics explicit. | |
| 338 | Counting Bits | Reuse bit counts of smaller integers and compare per-number scanning with a linear recurrence. | |
| 231 | Power of Two | Check whether exactly one bit is set, handling zero and negative numbers separately. | |
| 9 | Palindrome Number | Reverse only half the digits to check a palindrome, handling negatives, trailing zeros, and the middle digit of odd-length numbers. |
Core 7
| # | Problem | Approach | Rating |
|---|---|---|---|
| 190 | Reverse Bits | Reconstruct the result across exactly 32 bits without losing width because of leading zeros. | |
| 137 | Single Number II | Recover the uniquely occurring value through per-bit counts modulo the repetition count, handling negative two's-complement results. | |
| 260 | Single Number III | Partition by a set bit in the XOR difference and prove that each group leaves exactly one unique element. | |
| 201 | Bitwise AND of Numbers Range | Reduce bitwise AND over a consecutive interval to its common binary prefix instead of enumerating a large range. | |
| 69 | Sqrt(x) | Find the floor square root using integer boundaries and division-based comparisons to avoid multiplication overflow. | |
| 172 | Factorial Trailing Zeroes | Count factors by powers of five instead of computing a huge factorial, including repeated factors. | |
| 204 | Count Primes | Use 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
| # | Problem | Approach | Rating |
|---|---|---|---|
| 371 | Sum of Two Integers | Separate the sum without carries from the carries and handle fixed-width masking under Python's arbitrary-precision integers. | |
| 166 | Fraction to Recurring Decimal | Simulate long division and record each remainder's first position to locate the repeating cycle, handling signs and exact division. |
OA questions on this topic 199
- Count Powers of k in ReadingsMeta
- Count Colliding Object PairsMeta
- Three-Digit Numbers With All Distinct DigitsMeta
- Closest Land MarkMeta
- Count 3 Sister NumbersMeta
- System VulnerabilitiesAmazon
- Data Dependence SumAmazon
- Outlier ValueAmazon
- Pascal Triangle EncryptionAmazon
- Find Minimum MaximumAmazon