Skip to content

10-math-bit

  • Contains: count-number-of-bits.js, number-of-1-bits.js, reverse-bits.js, sum-of-two-integers.js.
  • Bit-manipulation practice in JavaScript.
  • Bitwise operations can replace loops for constant-time transformations.
  • Pay attention to JS 32-bit bitwise semantics and sign bits.
  • These are solution functions. Run with Node by adding a small driver, or paste into an online judge.

Bit manipulation replaces arithmetic with O(1) bitwise operations. Math problems test number theory fundamentals. Both are about recognizing the pattern, not brute-forcing.

Set bit i: x | (1 << i)
Clear bit i: x & ~(1 << i)
Toggle bit i: x ^ (1 << i)
Check bit i: x & (1 << i) != 0
Extract lowest set bit: x & (-x)
Clear lowest set bit: x & (x - 1)

Key property: a ^ a = 0 and a ^ 0 = a

Find the single number:

result = 0
for num in nums:
result ^= num
# result is the number that appears once

Interview problems: Single Number, Single Number II (use bit counting), Missing Number

Kernighan’s algorithm — count set bits in O(k) where k = number of set bits:

count = 0
while n:
n &= n - 1 # clear lowest set bit
count += 1

Interview problems: Number of 1 Bits, Counting Bits (for range), Hamming Distance

Multiply by 2^k: x << k
Divide by 2^k: x >> k
Check if power of 2: x > 0 and (x & (x-1)) == 0
Sum without +: carry = (a & b) << 1; a = a ^ b; repeat until carry == 0

Interview problems: Sum of Two Integers, Power of Two, Reverse Bits, Divide Two Integers

(a + b) mod m = ((a mod m) + (b mod m)) mod m
(a * b) mod m = ((a mod m) * (b mod m)) mod m
Modular exponentiation: pow(base, exp, mod) — built into Python
Modular inverse (when m is prime): pow(a, m-2, m)

Interview problems: Pow(x, n), Count Primes, Super Pow

def gcd(a, b):
while b:
a, b = b, a % b
return a
lcm = a * b // gcd(a, b)

Bezout’s identity: gcd(a, b) = a*x + b*y for some integers x, y (Extended Euclidean).

# n choose k
from math import comb # Python 3.8+
# or: dp[n][k] = dp[n-1][k-1] + dp[n-1][k] (Pascal's triangle)

Interview problems: Unique Paths (= C(m+n-2, m-1)), Pascal’s Triangle, Catalan Numbers

CompanyFavorite VariantDifficulty
GoogleBit manipulation + mathMedium-Hard
NVIDIABitwise ops (GPU relevance)Medium
Jane StreetNumber theory, probabilityHard
CitadelFast arithmetic, modular mathHard
HRTBit tricks for low-latencyHard
OperationBrute ForceBit/Math Trick
Is even?n % 2 == 0n & 1 == 0
Multiply by 2n * 2n << 1
Swap a, btempa ^= b; b ^= a; a ^= b
Abs valueif/else(n ^ (n >> 31)) - (n >> 31)
Average without overflow(a + b) / 2(a & b) + ((a ^ b) >> 1)