The Number of 1 Bits problem asks you to count the number of '1' bits (set bits) in the binary representation of a given unsigned integer. Also known as the "Hamming weight" or "popcount," this is a fundamental bit manipulation operation. The Number of 1 Bits coding problem has several elegant solutions with different trade-offs.
Apple, Cisco, Microsoft, Meta, Nvidia, Google, Bloomberg, and Adobe ask this because counting set bits is a fundamental operation in computer science — used in checksum computation, cryptography, and low-level systems programming. The divide and conquer and bit manipulation interview pattern is directly tested, and knowing multiple approaches demonstrates depth.
Multiple approaches:
n = n & (n-1) removes the lowest set bit. Count iterations until n=0. O(number of set bits).bin(n).count('1') or __builtin_popcount(n).Brian Kernighan's: each n & (n-1) clears exactly one set bit (the rightmost). Count iterations.
n=11 (binary: 1011). Apply Kernighan's:
Know Brian Kernighan's trick cold: while n: count++; n &= n-1. This is the most elegant O(popcount) solution and is guaranteed to impress interviewers. The insight: n & (n-1) clears the lowest set bit because subtracting 1 from n flips the lowest 1-bit and all bits below it, so AND eliminates them. This trick generalizes: counting set bits, checking if n is a power of 2 (n & (n-1) == 0), and removing the lowest set bit iteratively.