dsa1 min read
Single Number III — XOR Partition
Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.
Read →
webcoderspeed.com
1276 articles
Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.
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.