๐ง Replace arithmetic with bitwise โ full adder, bit-shifting, divide & conquer
Welcome, future bit manipulation master! ๐ What if we couldn't use +, -, or /? Bitwise operations can do ALL arithmetic โ and this guide will show you how. By the end, you'll be adding without +, dividing without /, reversing bits in 5 operations, and flipping images with a single XOR trick.
Full AdderBit DivisionReverse BitsXOR FlipBinary Linked ListArithmetic Tricks5 Problems
Foundation
๐ค Why Advanced Bit Ops Matter
Arithmetic operators like +, -, *, / feel fundamental โ but at the hardware level, CPUs have no such instructions. They have adders, shifters, and bitwise logic gates. Every arithmetic operation you write is compiled down to these primitives.
Knowing how to implement arithmetic using only bitwise operators is the ultimate signal of low-level mastery. These patterns appear in:
Embedded systems & firmware โ Microcontrollers often lack hardware multiply/divide. You implement it in software.
Cryptography โ Constant-time operations avoid timing side-channels. No branching on secret data.
Smart contracts (EVM) โ Gas costs make bitwise ops dramatically cheaper than arithmetic.
FAANG interviews โ "Add without +" is a staple question. Understanding the full adder circuit is expected.
Graphics & game dev โ Bit packing, color channels, and mask operations run at wire speed.
Operator
Hardware Cost
Bitwise Equivalent
Speed Gain
+ / -
Adder circuit (carry chain)
XOR + AND + shift
Identical (same gates)
*
Multiplier (many adders)
Shift + add (O(log n))
2-10ร slower (software)
/
Divider (non-trivial)
Shift + subtract (O(log n))
10-50ร slower (software)
%
Modulo = byproduct of /
Mask: n & (k-1) (for powers of 2)
Instant (single AND)
Key Insight
๐ก The Key Insight: Bitwise arithmetic is not a party trick โ it is how computers actually work. Every arithmetic operator in your high-level language is syntactic sugar over bit-level operations. Knowing the underlying circuit lets you write faster, more predictable code.
Core Concept
1. Sum Without + / - โ The Full Adder
The classic "add two integers without using + or -" problem is a rite of passage. To solve it, you must understand how binary addition works at the gate level.
Note
๐ง Real-World Analogy: Imagine you're adding two numbers on an abacus where each column can only hold 0 or 1. When both beads are down (0+0=0), no problem. When one is up (0+1 or 1+0=1), still fine. But when BOTH are up (1+1=2), the column overflows โ you need to CARRY 1 to the next column. XOR tells you the result without carry (1+1=0), AND tells you which columns need a carry. Then you shift the carry and add it again โ like fixing all the overflows in one pass.
The Full Adder โ Intuition
In binary, adding two bits produces a sum and a carry:
a
b
a ^ b (sum)
a & b (carry)
0
0
0
0
0
1
1
0
1
0
1
0
1
1
0
1
Key observation: XOR gives the sum without carry, AND gives the carry bits. The carry then needs to be shifted left by 1 (because it propagates to the next bit position) and added back to the XOR result. Repeat until there is no carry.
๐ Real-Time Thinking โ What Do I Know?
"I can't use + or -. But I know that at the hardware level, addition uses XOR for sum and AND for carry. Let me think... XOR of two bits gives the sum WITHOUT the carry: 0^0=0, 0^1=1, 1^0=1, 1^1=0. AND gives the carry: 0&0=0, 0&1=0, 1&0=0, 1&1=1. So a ^ b = sum without carry, a & b = carry bits. The carry needs to be added to the NEXT bit position (shifted left by 1). I repeat until carry = 0. This is the full-adder circuit in software!"
๐ Edge Cases to Consider
b = 0: No carry. The while loop doesn't execute. a ^ 0 = a. Returns a immediately.
a = b = 0: carry = 0, loop exits immediately. Returns 0. Correct.
a = -b (e.g., 5 and -5): Two's complement arithmetic. -5 = ~5 + 1. XOR and AND work on the bit pattern. 5 + (-5) = 0. Works correctly.
Overflow (e.g., 2^31-1 + 1): In 32-bit signed, this wraps to -2^31. Detect overflow by checking (a ^ result) & (b ^ result) < 0.
Large numbers beyond 32-bit: JavaScript bitwise ops truncate to 32-bit signed. For BigInt, the same algorithm works but with BigInt operators.
The Algorithm
example.js
function getSum(a, b) {
// carry = bits where both a AND b are 1
// a = bits where exactly one of a,b is 1 (sum without carry)
// b = carry shifted left โ to be added in next iteration
while (b !== 0) {
const carry = a & b; // 1. Find carry bits
a = a ^ b; // 2. Sum without carrying
b = carry << 1; // 3. Shift carry to correct positions
}
return a; // When carry is 0, a holds the sum
}
๐ Dry Run โ a = 5, b = 3
Let's trace getSum(5, 3) and watch the carry ripple through:
Iteration
a
b
carry = a & b
a = a ^ b
b = carry << 1
1
101 (5)
011 (3)
001 (1)
110 (6)
010 (2)
2
110 (6)
010 (2)
010 (2)
100 (4)
100 (4)
3
100 (4)
100 (4)
100 (4)
000 (0)
1000 (8)
4
000 (0)
1000 (8)
000 (0)
1000 (8) โ
000 (0)
Sum BitsSum Bits diagram; follow the annotated steps in the surrounding explanation.
Why This Works
At the transistor level, a full adder circuit implements exactly these two equations:
Sum = A XOR B XOR CarryIn
CarryOut = (A AND B) OR (CarryIn AND (A XOR B))
Our loop simulates a ripple-carry adder โ each iteration pushes the carry one position left until it reaches zero. In hardware, this propagation happens in parallel (carry-lookahead), but in software we must loop.
Tip
โก Performance Note: The number of iterations equals the position of the highest set carry bit. For 32-bit integers, worst case is 32 iterations (e.g., adding 1 to -1 wraps through all bits).
2. Divide Without / โ Bit-Shifting Long Division
Division is the most expensive arithmetic operation. A hardware divider takes 10-50ร more cycles than addition. When no / instruction exists (common in embedded DSPs and early RISC chips), you implement division using repeated subtraction with bit shifting.
Note
๐ฐ Real-World Analogy: Imagine you have $1000 and need to give $3 to as many people as possible. Instead of giving $3 at a time (333 iterations), you think: "What's the biggest chunk I can give?" $3 ร 256 = $768, leaving $232. Then $3 ร 64 = $192, leaving $40. Then $3 ร 8 = $24, leaving $16. Then $3 ร 4 = $12, leaving $4. Then $3 ร 1 = $3, leaving $1. Total: 256+64+8+4+1 = 333 people, remainder $1. That's only 5 iterations instead of 333 โ this is exactly bit-shifting long division!
๐ค The Intuition
How would you compute 10 รท 3 without division? The naive approach:
The trick: instead of subtracting the divisor one at a time, shift it left (multiply by powers of two) and subtract the largest possible chunk at each step. This is exactly how long division works in binary.
๐ Real-Time Thinking โ What Do I Know?
"Division is repeated subtraction. The naive way: subtract divisor from dividend until we can't anymore. That's O(quotient) โ way too slow for large numbers. But what if I subtract the divisor MULTIPLIED by a power of two? I can shift the divisor left until it's just under the dividend, subtract that chunk, then continue with the remainder. That's O(log dividend) โ at most 31 iterations for 32-bit integers. This is exactly how long division works in binary!"
The Algorithm
example.js
function divide(dividend, divisor) {
// Handle edge case: division by zero
if (divisor === 0) throw new Error("Division by zero");
// Track sign, work with positive values
const negative = (dividend < 0) !== (divisor < 0);
let dvd = Math.abs(dividend);
let dvs = Math.abs(divisor);
let quotient = 0;
// Find the largest shift such that (divisor << shift) <= dividend
let shift = 0;
while (dvs << (shift + 1) <= dvd && dvs << (shift + 1) > 0) {
shift++;
}
// Repeatedly subtract the largest possible chunk
while (dvd >= dvs) {
while (dvs << shift > dvd) {
shift--; // Overshot โ reduce shift
}
dvd -= dvs << shift; // Subtract the chunk
quotient += 1 << shift; // Add to quotient
}
return negative ? -quotient : quotient;
}
๐ Understanding 10 รท 3
Let's trace through step-by-step:
Step
Operation
Remainder
Quotient
Why
1
Find max shift
10
0
3 << 1 = 6 โค 10, 3 << 2 = 12 > 10 โ shift = 1
2
10 - (3 << 1) = 10 - 6
4
2 (adds 1 << 1)
Subtract largest chunk: 6
3
4 - (3 << 0) = 4 - 3
1
3 (adds 1)
Subtract divisor: 3
4
1 < 3 โ stop
1
3
โ Result: 3, remainder 1
Divide BitsDivide Bits diagram; follow the annotated steps in the surrounding explanation.
Time Complexity Analysis
Approach
Time
Explanation
Naive subtraction
O(quotient)
Subtract divisor one at a time โ 10โน iterations for large numbers
Bit-shifting division
O(log dividend)
Number of bits in the dividend โ at most 31 iterations for 32-bit ints
Warning
โ ๏ธ Overflow Gotcha: The expression dvs << (shift + 1) > 0 is critical in the first while loop. Without the positive check, dvs << shift can overflow to a negative number in JavaScript's 32-bit signed integer arithmetic, causing an infinite loop.
Reversing the bits of a 32-bit unsigned integer is a classic problem with a surprisingly elegant solution. The naive approach (loop through each bit and swap) works in O(32) โ but the divide and conquer approach does it in just 5 operations, regardless of bit length.
The Divide & Conquer Strategy
Think of it as recursive swapping on a 32-bit number:
Swap 16-bit halves
Swap 8-bit halves within each 16-bit block
Swap 4-bit halves (nibbles) within each 8-bit block
Swap 2-bit halves within each 4-bit block
Swap adjacent bits (1-bit blocks)
At each level, we use a bit mask to isolate the left and right halves, then swap them using shift and OR.
The Magic Masks
Step
Mask (hex)
Mask (binary)
Purpose
1
0xFFFF0000
11111111111111110000000000000000
Isolate high 16 bits
2
0x00FF00FF
00000000111111110000000011111111
Isolate byte pairs
3
0x0F0F0F0F
00001111000011110000111100001111
Isolate nibble pairs
4
0x33333333
00110011001100110011001100110011
Isolate 2-bit pairs
5
0x55555555
01010101010101010101010101010101
Isolate adjacent bits
The Implementation
example.js
function reverseBits(n) {
// Step 1: Swap 16-bit halves
n = (n >>> 16) | (n << 16);
// Step 2: Swap 8-bit halves within each 16-bit block
n = ((n & 0x00FF00FF) << 8) | ((n >>> 8) & 0x00FF00FF);
// Step 3: Swap 4-bit halves within each 8-bit block
n = ((n & 0x0F0F0F0F) << 4) | ((n >>> 4) & 0x0F0F0F0F);
// Step 4: Swap 2-bit halves within each 4-bit block
n = ((n & 0x33333333) << 2) | ((n >>> 2) & 0x33333333);
// Step 5: Swap adjacent bits (1-bit blocks)
n = ((n & 0x55555555) << 1) | ((n >>> 1) & 0x55555555);
return n >>> 0; // Convert to unsigned 32-bit
}
๐ Visual Walkthrough
Let's reverse n = 1 (00000001โ) โ 128 (10000000โ). For an 8-bit view (same pattern applies to 32-bit):
Reverse BitsReverse Bits diagram; follow the annotated steps in the surrounding explanation.
Key Insight
๐ The Pattern: (mask, shift, OR, mask, shift, OR) at decreasing sizes is known as a Benes network or butterfly network โ the same topology used in FFT and sorting networks. Once you see it, you find it everywhere.
Why This Is So Efficient
The naive approach โ looping over each bit โ takes 32 iterations with conditional logic inside each one. Divide & conquer does 5 bitwise operations with no branches. This matters in:
Cryptographic hash functions โ SHA-256, MD5 use bit reversal extensively
FFT / signal processing โ Bit-reversal permutation is a core step
Data compression โ Huffman coding and LZW use bit-level packing
Given a binary matrix (each cell is 0 or 1), we want to flip the image horizontally, then invert it. This means:
Flip horizontally โ reverse each row
Invert โ flip every 0 to 1 and every 1 to 0
Note
๐ผ๏ธ Real-World Analogy: Imagine you have a photo negative. You want to flip it horizontally (mirror image) AND invert the colors (negative to positive). Instead of doing two passes โ first flipping, then inverting โ you can do BOTH at once. When you swap two pixels from opposite sides, you also invert each one with ^1. It's like saying: "swap these two, and while you're at it, flip both." The XOR 1 trick handles both operations in a single expression!
๐ค The XOR Trick: ^1
Inverting a binary value is simply bit ^ 1. Since XOR with 1 flips a bit: 0 ^ 1 = 1, 1 ^ 1 = 0.
But here's the BEAUTIFUL part: we can combine the flip and invert into a single operation. When we swap two elements during the horizontal flip, we XOR each with 1 at the same time.
The Algorithm
example.js
function flipAndInvertImage(image) {
const n = image.length;
for (let i = 0; i < n; i++) {
let left = 0;
let right = n - 1;
while (left <= right) {
// XOR with 1 does both: swap AND invert in one shot!
// If left === right (middle element in odd-length row),
// we still need to invert it โ the XOR handles this too.
const temp = image[i][left] ^ 1;
image[i][left] = image[i][right] ^ 1;
image[i][right] = temp;
left++;
right--;
}
}
return image;
}
๐ Dry Run
Input: [[1,0,0],[0,1,0],[1,1,1]]
Row
Before
After flip + invert
Explanation
1
[1, 0, 0]
[1, 1, 0]
Reverse โ [0,0,1], then invert โ [1,1,0]
2
[0, 1, 0]
[1, 0, 1]
Reverse โ [0,1,0], then invert โ [1,0,1]
3
[1, 1, 1]
[0, 0, 0]
Reverse โ [1,1,1], then invert โ [0,0,0]
Why ^1 Works for Both Flip and Invert
example.js
// Traditional approach (separate steps):
// 1. Flip: reverse each row
// 2. Invert: for each cell, cell = cell ^ 1
// Combined approach (one pass):
// Swap left and right, but XOR each with 1 during the swap
const temp = image[i][left] ^ 1;
image[i][left] = image[i][right] ^ 1;
image[i][right] = temp;
// Because XOR is its own inverse, we can combine both operations.
// The result is exactly: (flip the row) AND (invert every bit).
Tip
โก Edge Case: When the row has odd length, the middle element (left === right) gets XOR'd with 1 and written back to itself โ effectively just inverting it. The swap is a no-op because it's the same position. This is correct behavior!
Time & Space
Time: O(nยฒ) โ we visit each element once. The two-pointer approach halves the number of swaps.
Space: O(1) โ we modify the matrix in-place. Only a single temp variable.
Given a singly linked list where each node holds a binary digit (0 or 1), return the decimal value. The most significant bit is at the head.
๐ Real-Time Thinking โ What Do I Know?
"I have a linked list of binary digits from MSB to LSB. This is like building a number from left to right. For binary "1011": start with 0. See 1: (0 << 1) | 1 = 1. See 0: (1 << 1) | 0 = 2. See 1: (2 << 1) | 1 = 5. See 1: (5 << 1) | 1 = 11. Each step shifts the accumulated value left (making room) and ORs in the new bit. This is Horner's method for polynomial evaluation โ most efficient way to compute 1ยท2ยณ + 0ยท2ยฒ + 1ยท2ยน + 1ยท2โฐ."
๐ค The Shift + Add Pattern
Think of it as constructing a binary number from left to right:
example.js
// For binary digits [1, 0, 1, 1]:
// Step 1: result = 0
// Step 2: result = (0 << 1) | 1 = 1
// Step 3: result = (1 << 1) | 0 = 2
// Step 4: result = (2 << 1) | 1 = 5
// Step 5: result = (5 << 1) | 1 = 11
// General pattern: result = (result << 1) | node.val
Each step shifts the existing value left (making room for the new bit) and OR's in the new bit. This is exactly how binary number construction works in hardware โ a shift register.
The Implementation
example.js
function getDecimalValue(head) {
let result = 0;
let current = head;
while (current !== null) {
// Shift left by 1 (multiply by 2), then add current bit
result = (result << 1) | current.val;
current = current.next;
}
return result;
}
๐ Understanding the Math
Why does (result << 1) | bit work? Let's trace 1-0-1-1:
Step
Current Bit
result (before)
result << 1
result = (<<1)|bit
Decimal
1
1
0000 (0)
0000 (0)
0001 (1)
1
2
0
0001 (1)
0010 (2)
0010 (2)
2
3
1
0010 (2)
0100 (4)
0101 (5)
5
4
1
0101 (5)
1010 (10)
1011 (11)
11
Key Insight
๐ Horner's Method: The shift-add pattern is actually Horner's method for polynomial evaluation, applied to binary numbers: 1ยท2ยณ + 0ยท2ยฒ + 1ยท2ยน + 1ยท2โฐ = ((1ยท2 + 0)ยท2 + 1)ยท2 + 1 = 11 Each step: multiply the accumulated result by 2 (shift left), add the next bit (OR). This is the most efficient way to evaluate polynomials โ only n multiplications and n additions.
Edge Cases
Empty list โ the while loop never executes, returns 0. Correct.
Single node โ (0 << 1) | val = val. Correct.
List too long โ JavaScript's 32-bit signed integer will overflow. Use BigInt for lists longer than 31 nodes.
Beyond the five core algorithms above, here is a curated collection of bit-level arithmetic tricks that replace common math operations. Commit these to memory โ they save cycles and impress interviewers.
Bit ArithmeticBit Arithmetic diagram; follow the annotated steps in the surrounding explanation.
Trick Reference Table
Operation
Bitwise Expression
Example
Notes
Multiply by 2โฟ
n << k
3 << 2 = 12
Overflows if n ร 2โฟ exceeds bit width
Divide by 2โฟ
n >> k (signed)
20 >> 2 = 5
>>> for unsigned. Rounds toward -โ for negatives.
Modulo (power of 2)
n & (k-1)
9 & 3 = 1
k MUST be a power of 2. Equivalent to n % k.
Isolate lowest set bit
n & -n
12 & -12 = 4
Two's complement: -n = ~n + 1. Only the rightmost 1 survives.
Clear lowest set bit
n & (n-1)
12 & 11 = 8
Used for popcount (Brian Kernighan's algorithm).
Check power of 2
n > 0 && (n & (n-1)) === 0
16 โ true
Powers of 2 have exactly one bit set. Clearing it gives 0.
Absolute value
(n ^ (n>>31)) - (n>>31)
-5 โ 5
For 32-bit signed integers. n>>31 is -1 for negative, 0 for positive.
Sign of number
(n >> 31) | (-n >>> 31)
-5 โ -1, 0 โ 0, 5 โ 1
Returns -1, 0, or 1.
Average no overflow
(a & b) + ((a ^ b) >> 1)
avg(2, 6) = 4
No overflow for large numbers. (a+b)/2 can overflow.
Swap without temp
a ^= b; b ^= a; a ^= b
a=3, b=5 โ a=5, b=3
XOR swap. Avoid for same variable (a ^= a โ 0).
XOR Swap โ Deep Dive
example.js
let a = 3, b = 5;
a = a ^ b; // a = 3 ^ 5 = 6
b = a ^ b; // b = 6 ^ 5 = 3 โ b now holds original a
a = a ^ b; // a = 6 ^ 3 = 5 โ a now holds original b
// After: a = 5, b = 3 โ swapped!
// Why? XOR is reversible: x ^ y ^ y = x
// Step 2: b = (a_original ^ b_original) ^ b_original = a_original
// Step 3: a = (a_original ^ b_original) ^ a_original = b_original
Warning
โ ๏ธ XOR Swap Trap: The XOR swap fails if a and b refer to the same memory location (e.g., swap(arr[i], arr[j]) when i === j). The variable becomes 0 because x ^ x = 0. Modern compilers optimize regular swaps to XOR swap anyway โ use a temp variable for clarity.
Key Insight
๐ก "A clever person solves a problem. A wise person avoids it." โ The best use of bitwise arithmetic tricks is knowing when not to use them. Modern compilers optimize n * 2 to n << 1 automatically. Write for clarity first, optimize with bitwise tricks only when profiling shows a bottleneck.
Interview Prep
๐ฏ Interview Cheat Sheet
Key Insight
Q1: How do you add two integers without using +? Use the full-adder circuit: while (b !== 0) { carry = a & b; a = a ^ b; b = carry << 1; }. XOR gives sum without carry, AND gives carry, shift left by 1, repeat until carry is 0.
Key Insight
Q2: How do you divide without using / or *? Bit-shifting long division: find the largest shift where (divisor << shift) <= dividend, then repeatedly subtract the largest possible chunk. Each iteration adds 2^shift to the quotient. O(log n) vs O(n) naive subtraction.
Key Insight
Q3: How do you reverse bits of a 32-bit integer efficiently? Divide & conquer with 5 masks: swap 16-bit halves, then 8-bit, 4-bit, 2-bit, 1-bit blocks. Each step uses (n & mask) << k | (n >>> k) & mask. Five operations total, no loops.
Key Insight
Q4: What does x ^ 1 do and how is it useful? Flips the least significant bit. 0 ^ 1 = 1, 1 ^ 1 = 0. Combined with a swap, this lets you flip-and-invert a binary image in one operation per pair.
Key Insight
Q5: How do you convert a binary linked list to integer? Use Horner's method / shift-add: result = (result << 1) | node.val, moving from head (MSB) to tail. Each step multiplies by 2 and adds the current bit. O(n) time, O(1) space.
Key Insight
Q6: What is n & (n-1) used for? Clears the lowest set bit. Used in Brian Kernighan's popcount algorithm, checking if n is a power of 2, and finding the next lower number with fewer set bits.
Summary
๐ Key Takeaways
Arithmetic operators (+ - * /) are syntactic sugar for bitwise operations. Every bitwise algorithm mirrors a hardware circuit.
Sum without +: use XOR for sum without carry, AND + shift for carry, repeat until carry = 0. This is the full-adder circuit in software.
Divide without /: bit-shifting long division reduces O(n) naive subtraction to O(log n). Find the largest shift, then subtract chunks.
Reverse bits: divide & conquer with 5 masks (0xFFFF0000, 0x00FF00FF, 0x0F0F0F0F, 0x33333333, 0x55555555) does it in 5 operations, no loops.
Flip an image: XOR with 1 (^1) inverts a bit. Combine flip + invert into one swap-per-pair using XOR for both operations.
Binary linked list to int: (result << 1) | node.val is Horner's method for polynomial evaluation โ O(n) time, O(1) space.
n & (n-1) clears the lowest set bit. n & -n isolates it. These are the two most versatile bit-level patterns.
n & (k-1) is equivalent to n % k only when k is a power of two. This is the fastest modulo operation possible.
XOR swap (a ^= b; b ^= a; a ^= b) works without a temp variable but fails when a and b are the same reference. Use temp for safety.
Know when NOT to use bit tricks: modern compilers optimize arithmetic into bitwise ops automatically. Write for clarity first.
Note
๐ฎ What's Next? Now that you've mastered advanced bit operations, head over to Bit Counting & Hamming Distance to learn about popcount and the Brian Kernighan algorithm!