Easy · XOR Popcount
Understand → Visualise → Practice.
Return how many bit positions differ between two non-negative integers.
a XOR b has a 1 exactly where a and b disagree, so the Hamming distance is the number of set bits in a XOR b.
Compute x = a ^ b.
Repeat x &= x − 1, which clears the lowest set bit each time.
The number of iterations is the number of differing positions.
O(number of set bits) time, at most O(log max(a, b)), and O(1) space.
Comparing decimal digits is wrong; the distance is about binary positions.
Read the full guide first: Bit Manipulation and Bitmask Patterns.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.