DevPath

← All problems

Hamming Distance

Easy bit-manipulation

Description

Return the number of bit positions at which two non-negative integers differ.

Constraints

0 <= a, b <= 10^9

Examples

Input: a = 1, b = 4

Output: 2

001 vs 100

Hints (1)
  • XOR marks differing bits; count the set bits of the result.

Solutions

Popcount of the XOR. · Time O(bits) · Space O(1)

func hammingDistance(a, b int) int {
    x := a ^ b
    count := 0
    for x > 0 {
        x &= x - 1
        count++
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account