Skip to content

Bit Manipulation & Math

Reach for it when the problem says

  • "Without extra space"
  • single number
  • powers of two
  • digits
Solved
0/32Solved
Problems
32Problems
Variants
6Variants

Problems

6 variants

XOR cancellation

0 of 4 solved

Counting set bits

0 of 6 solved

Masks and shifts

0 of 6 solved

Arithmetic by hand

0 of 6 solved

Digit manipulation

0 of 6 solved

Number theory

0 of 4 solved

Pattern guide

Bit and math problems look like a grab bag, but they share one move: instead of building a data structure, you use a property of numbers to get the answer in O(1) extra space. Interviewers like them because the brute force is easy (a hash map, a string conversion, a big loop) and the follow-up "can you do it without extra space?" separates people who know the tools from people who do not.

What it is

Every integer is stored as bits. Operators like & (AND), | (OR), ^ (XOR), ~ (NOT), << and >> (shifts) act on all bits at once, so one operation does 32 tiny comparisons in a single step. Math problems use the same idea with decimal digits (% 10 and // 10) or with facts like "a trailing zero needs a factor of 5".

Here is the most famous trick. XOR outputs 1 where two bits differ, so x ^ x = 0 and x ^ 0 = x. XOR a whole list together and every pair cancels.

XOR the list [4, 1, 2, 1, 2]
4
0
1
1
2
2
1
3
2
4
acc = 000 ^ 100 = 100

Start with acc = 0. XOR in 4 (binary 100): acc is now 4.

1/5

Order did not matter, and no memory was used beyond one integer. That is the flavour of the whole category.

Python integers vs JavaScript numbers

This matters in almost every bit problem, so learn it once.

PythonJavaScript / TypeScript
Integer sizeUnbounded: 2 ** 100 is exactNumbers are 64-bit floats, exact up to 2^53 - 1
Bitwise operatorsWork on the full integer, any sizeConvert to a signed 32-bit integer first
1 << 312147483648-2147483648 (the sign bit)
Negative numbersAct like infinite two's complement: -1 is "all ones forever"Exactly 32 bits of two's complement
Unsigned resultAlways non-negative if you never go negativeUse x >>> 0 to reread the 32 bits as unsigned
Unsigned right shiftNot needed>>> fills with zeros; >> copies the sign bit

Two consequences come up again and again. In JavaScript, anything that sets bit 31 turns negative, so problems with unsigned 32-bit answers (Reverse Bits) need >>> 0, and values like 2^31 (from negating -2^31) cannot go through & or >> safely. In Python, nothing ever overflows, so problems that rely on 32-bit wraparound (Sum of Two Integers) need a manual mask, & 0xFFFFFFFF, and a final conversion back to a signed value.

Predict the outputJavaScript

What does this print?

console.log(1 << 31, (1 << 31) >>> 0);
Need a nudge? Hints walk you through it.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"appears twice except one", "appears three times"XOR cancellation, or counting each bit modulo k
"without extra space", "O(1) extra space"A running integer instead of a hash map
"power of two", "power of four"One set bit: n & (n - 1) == 0, plus a mask
"number of 1 bits", "Hamming distance"XOR to mark differences, then count set bits
"unsigned 32-bit", "reverse the bits"Shifts and masks, with >>> 0 in JavaScript
"without using +", "without *, / or %"Rebuild arithmetic from XOR, AND, shifts and doubling
"digits", "reverse the integer", "palindrome number"Pop with % 10, push with * 10
"stored as a string", "too large for an integer"Schoolbook arithmetic with a carry
"primes", "factorial", "greatest common divisor"Number theory: sieve, factor counting, Euclid

Constraint clues

ConstraintWhat it suggests
-2^31 <= x <= 2^31 - 132-bit thinking: overflow checks, the sign bit, at most 31 or 32 loop steps
0 <= n <= 2^32 - 1Unsigned values above JavaScript's signed range: use >>> and >>> 0
nums.length <= 10^5 with "O(1) space"One linear pass with an accumulator, not sorting
length <= 10^4 for a number given as a stringDigit-by-digit arithmetic, O(n)
n <= 5 * 10^6 with "primes"A sieve over an array of size n
A range like [left, right] up to 2^31Do not iterate; find a property of the endpoints

Input and output shape clues

  • A single integer in, a single integer or boolean out: almost always bits or digits. Ask "what does this look like in binary?"
  • An array where everything is paired except a few: XOR, or per-bit counts.
  • Numbers as strings or digit arrays: arithmetic by hand, right to left with a carry.
  • "Sum over all pairs" of a bitwise quantity: handle one bit position at a time and count pairs with multiplication.

Looks like it but isn't

  • Arrays and hashing. A count map solves Single Number instantly. It is the right first answer, but when the prompt says O(1) space, it is a decoy.
  • Two pointers on a sorted copy. Sorting groups duplicates, but costs O(n log n) and rarely matches the intended bound.
  • Greedy or DP for Integer to Roman. It smells like coin change, but the Roman table is built so that "largest that fits" is always right. No table of subproblems is needed.
  • Binary search for Divide Two Integers. Checking a guess needs multiplication, which is banned. Doubling the divisor is the bit-level version of the same idea.
Quick check
Which prompt most strongly suggests a bit trick rather than a hash map?
Need a nudge? A hint rules out a wrong answer.

The sub-patterns

XOR cancellation

When it applies: things come in pairs and you need what is left over, or you need two numbers whose XOR is something. The tools are x ^ x = 0, x ^ 0 = x, order not mattering, and a ^ b = c meaning a ^ c = b.

When two values are left over (Single Number III), the total XOR is a ^ b. Its lowest set bit, x & -x, is a position where a and b differ, so it splits the array into two groups that each hold one single.

Single Number III on [1, 2, 1, 3, 2, 5]
1
0
2
1
1
2
3
3
2
4
5
5
both = 3 ^ 5 = 6 (110)

XOR everything. The pairs cancel, leaving 3 ^ 5 = 6, binary 110.

1/4
Python
def single_number(nums: list[int]) -> int: acc = 0 for num in nums: acc ^= num return acc def two_singles(nums: list[int]) -> list[int]: both = single_number(nums) low = both & -both first = 0 for num in nums: if num & low: first ^= num return [first, both ^ first] print(single_number([4, 1, 2, 1, 2]))print(two_singles([1, 2, 1, 3, 2, 5]))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Best-known problems: Single Number, Missing Number, Single Number III, Maximum XOR of Two Numbers in an Array.

Counting set bits

When it applies: the answer is a count of 1 bits, or you must reason about each bit position separately (Hamming distances, values that appear three times, OR equations).

The core tool is n & (n - 1), which clears the lowest set bit. Subtracting 1 flips the lowest 1 to 0 and every 0 below it to 1, and the AND keeps only the bits that did not change.

Clearing the lowest set bit of 44
b5b4b3b2b1b0
n101100
n - 1
n & (n - 1)

n = 44 is 101100. Its lowest set bit is bit 2.

1/3

When you need per-position reasoning, loop over the 32 positions and count. For values that appear three times, a bit whose count is not divisible by 3 belongs to the single value.

Python
def popcount(n: int) -> int: count = 0 while n: n &= n - 1 count += 1 return count def once_among_triples(nums: list[int]) -> int: result = 0 for bit in range(32): if sum((x >> bit) & 1 for x in nums) % 3: result |= 1 << bit # Python has no 32-bit wrap, so reread bit 31 as the sign. return result - (1 << 32) if result >= 1 << 31 else result print(popcount(44))print(once_among_triples([-2, -2, 1, 1, 4, 1, 4, 4, -4, -2]))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(number of set bits) for one popcount; O(32 · n) for per-bit counting. Best-known problems: Number of 1 Bits, Counting Bits, Total Hamming Distance, Single Number II.

Masks and shifts

When it applies: you need to test, set, clear, flip or move particular bits. A mask is a number whose 1 bits mark the positions you care about.

GoalExpression
Is bit i set?(n >> i) & 1
Set bit in OR (1 << i)
Clear bit in & ~(1 << i)
Flip bit in ^ (1 << i)
Lowest set bit onlyn & -n
Exactly one bit set?n > 0 and n & (n - 1) == 0
Bits at even positions0x55555555 (0101...0101)
Complement of 10 with a width mask
b3b2b1b0
n1010
mask
n ^ mask

n = 10 is 1010. We want to flip only these four bits; ~n would also flip the endless leading zeros and go negative.

1/3
Python
def reverse_bits(n: int) -> int: result = 0 for _ in range(32): result = (result << 1) | (n & 1) n >>= 1 return result def is_power_of_four(n: int) -> bool: return n > 0 and n & (n - 1) == 0 and n & 0x55555555 != 0 print(reverse_bits(1))print(is_power_of_four(16), is_power_of_four(8))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(1) for fixed-width tricks, O(32) for loops over all bits. Best-known problems: Reverse Bits, Power of Two, Power of Four, Bitwise AND of Numbers Range.

Predict the outputPython

What does this print?

print(5 & 3, 5 | 3, 5 ^ 3, 5 << 1, 5 >> 1)
Need a nudge? Hints walk you through it.

Arithmetic by hand

When it applies: an operator is banned, or the numbers are too big for any integer type, so you rebuild arithmetic the way you learned it on paper.

For addition with no +: the sum digit of a column is XOR and the carry is AND. So a ^ b adds everything without carrying, and (a & b) << 1 is the carries moved one column left. Repeat until there are no carries.

5 + 3 without the + operator
b3b2b1b0
a0101
b (carry)0011

a = 5 (0101), b = 3 (0011).

1/4

For strings or digit arrays, walk from the right with a carry: total = carry + digits, write total % base, carry total // base. For multiplication, digit i times digit j lands at position i + j + 1. For division and powers, use doubling: subtract the biggest doubled divisor that fits, or square the base and halve the exponent.

Python
def get_sum(a: int, b: int) -> int: mask = 0xFFFFFFFF a, b = a & mask, b & mask while b: a, b = a ^ b, ((a & b) << 1) & mask return a if a <= 0x7FFFFFFF else ~(a ^ mask) def my_pow(x: float, n: int) -> float: if n < 0: x, n = 1 / x, -n result = 1.0 while n: if n & 1: result *= x x *= x n >>= 1 return result print(get_sum(-5, -7), my_pow(2.0, 10))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(32) for bitwise addition, O(log n) for doubling and fast power, O(n) or O(m · n) for string arithmetic. Best-known problems: Sum of Two Integers, Add Binary, Plus One, Multiply Strings, Pow(x, n).

Put it in order5 steps

Put the steps of bitwise addition in Python in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Digit manipulation

When it applies: the problem talks about decimal digits, symbols with values (Roman numerals), or positional systems (spreadsheet columns). Two moves cover nearly everything:

  • Pop the last digit: digit = x % 10, then x = x // 10.
  • Push a digit on the right: result = result * 10 + digit.

Popping from one number and pushing onto another reverses it. Changing 10 to 26 reads spreadsheet columns.

Reversing 123 by popping and pushing
1
0
2
1
3
2
x = 123result = 0

Start with x = 123, result = 0.

1/4
Python
def reverse(x: int) -> int: limit = 2**31 - 1 sign = -1 if x < 0 else 1 x, result = abs(x), 0 while x: x, digit = divmod(x, 10) if result > (limit - digit) // 10: return 0 result = result * 10 + digit return sign * result def title_to_number(title: str) -> int: number = 0 for ch in title: number = number * 26 + (ord(ch) - ord("A") + 1) return number print(reverse(-123), reverse(1534236469), title_to_number("AB"))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(number of digits), which is O(log n). Best-known problems: Reverse Integer, Palindrome Number, Happy Number, Roman to Integer.

Number theory

When it applies: primes, divisibility, factorials, or greatest common divisors. The answer comes from a known fact, so the work is recognising which fact.

  • Sieve of Eratosthenes: to find all primes below n, cross out multiples of each prime, starting from p * p.
  • Counting prime factors: trailing zeros of n! are the 5s in it, n // 5 + n // 25 + ....
  • Euclid's gcd: gcd(a, b) = gcd(b, a % b), ending when b is 0.
Sieve of Eratosthenes below 20
2
0
3
1
4
2
5
3
6
4
7
5
8
6
9
7
10
8
11
9
12
10
13
11
14
12
15
13
16
14
17
15
18
16
19
17

Every number from 2 to 19 starts marked as prime.

1/4
Python
def count_primes(n: int) -> int: if n < 3: return 0 is_prime = [True] * n is_prime[0] = is_prime[1] = False p = 2 while p * p < n: if is_prime[p]: for m in range(p * p, n, p): is_prime[m] = False p += 1 return sum(is_prime) def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a print(count_primes(20), gcd(12, 18))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: the sieve is O(n log log n) time and O(n) space; Euclid is O(log min(a, b)); factor counting is O(log n). Best-known problems: Count Primes, Factorial Trailing Zeroes, Greatest Common Divisor of Strings.

Decision checklist

Ask in this order: is there a pairing to cancel? Is the answer about which bits are set? Do I need to touch specific positions? Is an operator banned or is the number too big? Is it about decimal digits? Is it a fact about primes or divisors?

Match the pairs0/6 matched

Match each problem to its sub-pattern.

Choose an item, then its match on the other side.

Traps

  • JavaScript's sign bit. 1 << 31 is negative, and >> copies the sign bit in. For unsigned answers, finish with >>> 0 and shift with >>>. Never push values of 2^31 or more through &, | or >>; use % and Math.floor(n / 2) instead (Pow(x, n), Divide Two Integers).
  • Python's missing overflow. Problems that assume 32-bit wraparound loop forever without & 0xFFFFFFFF (Sum of Two Integers with -1 + 1). When you build a 32-bit value bit by bit, convert bit 31 back to a sign yourself (Single Number II).
  • Precedence. In Python, & binds tighter than ==, so n & (n - 1) == 0 is fine. In JavaScript, === binds tighter than &, so you must write (n & (n - 1)) === 0.
  • Zero and negatives. 0 & (0 - 1) is 0, so the power-of-two test needs n > 0. The complement of 0 is 1, not 0.
  • Stopping too early. Reverse Bits must run 32 times even when n hits 0, because leading zeros become trailing zeros.
  • Overflow checks after the fact. In Reverse Integer the check must happen before result * 10 + digit.
  • Truncation vs floor. -7 / 2 truncated toward zero is -3, but Python's -7 // 2 is -4. Work on absolute values and apply the sign at the end.

Always test: 0, 1, a negative number, the smallest and largest 32-bit values (-2147483648, 2147483647), a power of two, and an all-ones value.

Quick check
Your Python Sum of Two Integers loops forever on get_sum(-1, 1). Why?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
XOR (^)
Outputs 1 where two bits differ. x ^ x = 0 and x ^ 0 = x, so pairs cancel.
n & (n - 1)
Clears the lowest set bit of n. It is 0 exactly when n has at most one set bit.
Two's complement
How negative integers are stored: -x is ~x + 1. It makes x & -x isolate the lowest set bit.
Mask
A number whose 1 bits mark the positions you want to test, keep or flip, such as 0xFFFFFFFF or 0x55555555.
>>> 0
JavaScript idiom that rereads a 32-bit value as unsigned, turning -2147483648 into 2147483648.
Sieve of Eratosthenes
Finds all primes below n by crossing out multiples of each prime, starting at its square.