Common bit tricks
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Almost every bit-manipulation interview question is built from six one-line idioms: four operations on the k-th bit (1 << k) and two operations on the lowest set bit (n & (n - 1) and n & -n). Once you understand why subtracting 1 flips the rightmost 1 bit, you never have to memorize them blindly.
Check, set, clear and toggle a bit
Let bit positions be 0-indexed from the right (so bit 0 is the 2⁰ = 1 place and bit k is the 2ᵏ place).
Example 1 · Check, Set, Clear, and Toggle the k-th Bit
public class KthBitOperations { private static String bin8(int x) { return String.format("%8s", Integer.toBinaryString(x & 0xFF)).replace(' ', '0'); }
public static void main(String[] args) { int n = 0b0010_1010; // 42 (bits 1, 3, 5 are set) System.out.println("Initial n: " + bin8(n) + " (" + n + ")");
System.out.println("Bit 3 is set? " + ((n & (1 << 3)) != 0)); System.out.println("Bit 2 is set? " + ((n & (1 << 2)) != 0));
int setBit2 = n | (1 << 2); int clearBit3 = n & ~(1 << 3); int toggleBit0 = n ^ (1 << 0);
System.out.println("Set bit 2: " + bin8(setBit2) + " (" + setBit2 + ")"); System.out.println("Clear bit 3: " + bin8(clearBit3) + " (" + clearBit3 + ")"); System.out.println("Toggle bit 0: " + bin8(toggleBit0) + " (" + toggleBit0 + ")"); }}Initial n: 00101010 (42) Bit 3 is set? true Bit 2 is set? false Set bit 2: 00101110 (46) Clear bit 3: 00100010 (34) Toggle bit 0: 00101011 (43)
What this code does
n | (1 << 2)turns on bit 2 (2² = 4), adding 4 to42to produce46.n & ~(1 << 3)clears bit 3 (2³ = 8), subtracting 8 from42to produce34.
The mask 1 << k has a 1 at bit k and 0 everywhere else, while ~(1 << k) has a 0 at bit k and 1 everywhere else. Combining n with that mask gives the four fundamental operations:
- Check bit
k:(n & (1 << k)) != 0(or((n >>> k) & 1) == 1). Note: prefer!= 0over> 0because whenk == 31,1 << 31is negative (Integer.MIN_VALUE)! - Set bit
kto1:n | (1 << k). - Clear bit
kto0:n & ~(1 << k). - Toggle (flip) bit
k:n ^ (1 << k).
Counting set bits and Integer.bitCount
The number of 1 bits in n is called its popcount or Hamming weight. A simple loop shifts through all 32 bits (count += n & 1; n >>>= 1;), always taking 32 steps.
public class CountBits { public static void main(String[] args) { int n = 40; // 0010_1000 System.out.println(n & (n - 1)); // lowest 1 bit cleared: 0010_0000 int count = 0; for (int m = n; m != 0; m &= (m - 1)) { count++; // one step per 1 bit } System.out.println(count); System.out.println(Integer.bitCount(n)); }}32 2 2
Brian Kernighan's trick (n & (n - 1)) is much cleverer: what happens when you subtract 1 from any non-zero integer n? Suppose n = 40 (0010_1000). Subtracting 1 borrows from the lowest set 1 bit (at bit 3), turning 0010_1000 into n - 1 = 39 (0010_0111). Notice that everything to the left of bit 3 stayed identical, while bit 3 and everything to its right flipped! Therefore, n & (n - 1) clears the lowest set 1 bit of n in one operation (0010_1000 & 0010_0111 = 0010_0000 = 32).
Looping while (n != 0) { n &= (n - 1); count++; } runs only once per 1 bit! And in production Java, Integer.bitCount(n) (and Long.bitCount(n)) compiles down to a single hardware POPCNT CPU instruction.
n & (n - 1) clears the lowest 1 bit
Step 1 of 3
- n
- 40
Example 2 · Brute force: test all 32 bit positions (O(32) time, O(1) space)
public class CountBitsAllPositions { public static int countBits(int n) { int count = 0; for (int k = 0; k < 32; k++) { if ((n & (1 << k)) != 0) { count++; } } return count; }
public static void main(String[] args) { System.out.println("bits in 40: " + countBits(40)); System.out.println("bits in 255: " + countBits(255)); System.out.println("bits in -1: " + countBits(-1)); }}bits in 40: 2 bits in 255: 8 bits in -1: 32
What this code does
- Each position k is tested with
n & (1 << k), so the loop always runs 32 times, even for a small number like 40. - It works for negative numbers too, because
-1has all 32 bits set. It is the slowest of the three because it ignores how many 1 bits there really are.
Example 3 · Better: shift right until nothing is left (O(highest 1 bit) time, O(1) space)
public class CountBitsShifting { public static int countBits(int n) { int count = 0; while (n != 0) { count += n & 1; n >>>= 1; } return count; }
public static void main(String[] args) { System.out.println("bits in 40: " + countBits(40)); System.out.println("bits in 255: " + countBits(255)); System.out.println("bits in 1: " + countBits(1)); }}bits in 40: 2 bits in 255: 8 bits in 1: 1
What this code does
n >>>= 1drops the lowest bit each time, and the loop stops as soon as n is 0. For 40 that is 6 steps instead of 32.- It is faster than the brute force because the leading zeros are never visited. A negative number still needs 32 steps, because its top bit is 1.
Trace the code
Count the 1 bits of 44
Step through the loop and watch n lose one 1 bit each time.
Variables
- n
- 44
Output
(nothing printed yet)Line 3n is 44, which is 101100 in binary: three 1 bits.
Integer.bitCount(n) for clean library code, and write the n &= (n - 1) loop when the interviewer asks how to implement bit counting from scratch.Power-of-two check
Which positive integers have exactly one 1 bit in binary? The powers of two: 1 = 1₂, 2 = 10₂, 4 = 100₂, 8 = 1000₂, 16 = 10000₂, and so on!
Example 4 · Optimal: Brian Kernighan's n & (n - 1), power of two and lowest set bit (O(number of 1 bits) time, O(1) space)
public class KernighanAndLowestBit { public static int countSetBits(int n) { int count = 0; while (n != 0) { n &= (n - 1); // Clears the lowest set bit each step! count++; } return count; }
public static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }
public static void main(String[] args) { int x = 40; // 0010_1000 (bits 3 and 5 set: 8 + 32) System.out.println("40 in binary: " + Integer.toBinaryString(x)); System.out.println("40 & 39 (clear lowest): " + (x & (x - 1)) + " (" + Integer.toBinaryString(x & (x - 1)) + ")"); System.out.println("40 & -40 (isolate low): " + (x & -x) + " (" + Integer.toBinaryString(x & -x) + ")"); System.out.println("countSetBits(40): " + countSetBits(40) + " vs Integer.bitCount: " + Integer.bitCount(40)); System.out.println("isPowerOfTwo(64): " + isPowerOfTwo(64)); System.out.println("isPowerOfTwo(40): " + isPowerOfTwo(40)); System.out.println("isPowerOfTwo(0): " + isPowerOfTwo(0)); }}40 in binary: 101000 40 & 39 (clear lowest): 32 (100000) 40 & -40 (isolate low): 8 (1000) countSetBits(40): 2 vs Integer.bitCount: 2 isPowerOfTwo(64): true isPowerOfTwo(40): false isPowerOfTwo(0): false
What this code does
- For
x = 40(101000),x & (x - 1)strips the8bit and leaves32(100000), whilex & -xisolates the8bit (1000). - Notice that
(x & (x - 1)) + (x & -x) == 32 + 8 == 40 == xalways holds! - It beats shifting because
n & (n - 1)jumps straight to the next 1 bit: the loop runs once per 1 bit, not once per position.
Since n & (n - 1) clears the lowest 1 bit, a positive integer n has only one 1 bit if and only if clearing that single 1 bit leaves 0: boolean isPowerOfTwo = (n > 0) && ((n & (n - 1)) == 0);. Never forget the n > 0 check: 0 has zero 1 bits (0 & -1 == 0) and Integer.MIN_VALUE has a single 1 in the sign bit, yet neither is a positive power of two!
Lowest set bit
While n & (n - 1) clears the lowest set bit, n & -n isolates the lowest set bit (returning a power of two with only that lowest 1 bit kept).
Example 5 · Built-in Integer Bit Helpers in Java 17
public class IntegerBitHelpersDemo { public static void main(String[] args) { int n = 52; // 0b110100 = 32 + 16 + 4 System.out.println("n = " + n + " (0b" + Integer.toBinaryString(n) + ")"); System.out.println("Integer.bitCount(n): " + Integer.bitCount(n)); System.out.println("Integer.lowestOneBit(n): " + Integer.lowestOneBit(n)); System.out.println("Integer.highestOneBit(n): " + Integer.highestOneBit(n)); System.out.println("Integer.numberOfTrailingZeros(n): " + Integer.numberOfTrailingZeros(n)); System.out.println("Integer.numberOfLeadingZeros(n): " + Integer.numberOfLeadingZeros(n)); }}n = 52 (0b110100) Integer.bitCount(n): 3 Integer.lowestOneBit(n): 4 Integer.highestOneBit(n): 32 Integer.numberOfTrailingZeros(n): 2 Integer.numberOfLeadingZeros(n): 26
What this code does
52is32 + 16 + 4: its lowest set bit has value4(at index2, which equalsnumberOfTrailingZeros(52)).- Its highest set bit has value
32(at index5), leaving 31 - 5 = 26 leading zeros in a 32-bitint.
Why does n & -n work? In two's complement, -n == ~n + 1. For n = 40 (0010_1000), ~n is 1101_0111, and adding 1 carries across the trailing ones back into bit 3, giving -40 = 1101_1000. ANDing 0010_1000 & 1101_1000 cancels everything to the left of bit 3 and leaves 0000_1000 (8)! Java also provides built-in Integer helpers for highest and lowest bits: Integer.lowestOneBit(n) (which is n & -n), Integer.highestOneBit(n), Integer.numberOfTrailingZeros(n), and Integer.numberOfLeadingZeros(n).
Next step
Check your understanding
10 quick questions