dsa1 min read
Number of 1 Bits — Brian Kernighan
Count set bits (popcount). Brian Kernighan: n & (n-1) clears the lowest set bit; count how many operations until n=0.
Read →
1575 articles
Count set bits (popcount). Brian Kernighan: n & (n-1) clears the lowest set bit; count how many operations until n=0.
Count set bits for all numbers 0..n. DP: dp[i] = dp[i >> 1] + (i & 1). Remove last bit and check if it was set.
Reverse bits of a 32-bit unsigned integer. Shift result left and input right 32 times, taking last bit each time.
Find missing number in 0..n array. XOR approach: XOR all indices with all values, duplicate indices cancel. Or math: n*(n+1)/2 - sum.
Add two integers without + or - operators. Simulate: sum = a XOR b (no carry), carry = (a AND b) << 1. Repeat until carry = 0.