HomeBit Manipulation
Bit Manipulation
AND, OR, XOR and shifts — the classic constant-space tricks.
24 shown
- OverviewAND · OR · XOR · shifts · the classic tricksanimatedEasy
- Single NumberXOR fold · pairs cancelanimatedEasy
- Number of 1 BitsHamming weight · n & (n − 1)animatedEasy
- Missing NumberXOR index ⊕ value · pairs cancelanimatedEasy
- Practice problems
- Introduction to Bits and TricksAND, OR, XOR and the shiftsEasy
- Check if the i-th bit is Set or NotShift the bit down, or the mask upEasy
- Check if a Number is Odd or NotThe lowest bit is the parityEasy
- Check if a Number is Power of 2 or NotExactly one bit setEasy
- Count the Number of Set BitsBrian Kernighan: clear the lowest set bitanimatedEasy
- Set/Unset the rightmost unset bitOR with n+1Easy
- Swap Two NumbersThree XORs, no temporaryEasy
- Divide two numbers without multiplication and divisionSubtract the largest shifted divisorMedium
- Minimum Bit Flips to Convert NumberCount the set bits of the XORMedium
- Single Number - IXOR everything; the pairs vanishanimatedMedium
- Power Set Bit ManipulationEach number 0..2^n-1 is a subsetMedium
- XOR of numbers in a given rangePrefix XOR has a four-case patternMedium
- Single Number - IIISplit the array on one differing bitanimatedMedium
- Print Prime Factors of a NumberDivide out each factor as you find itHard
- Divisors of a NumberPair them up around the square rootEasy
- Count primes in range L to RSieve of Eratosthenes, then countHard
- Prime factorisation of a NumberSmallest-prime-factor sieveHard
- Pow(x,n)Square and multiply, driven by the bitsanimatedEasy
- Reverse BitsShift out one side, shift in the otherMedium
- Sum of Two IntegersXOR adds, AND finds the carriesMedium