GoLang: Compute the Hamming Distance


The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.

Example 1:
Input: x = 1, y = 4
Output: 2

Explanation:

1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

Example 2:
Input: x = 3, y = 1
Output: 1

0 <= x, y <= pow(2, 31) – 1

Hamming Distance in GoLang

XOR operation is same as other languages which uses ^ symbol. The Golang uses “for” keyword for a “while” loop. And the x&=x-1 removes the rightmost set bit.

1
2
3
4
5
6
7
8
9
func hammingDistance(x int, y int) int {
    x ^= y
    var ans = 0
    for x > 0 {
        ans += 1
        x &= x - 1
    }
    return ans
}
func hammingDistance(x int, y int) int {
    x ^= y
    var ans = 0
    for x > 0 {
        ans += 1
        x &= x - 1
    }
    return ans
}

Hamming Weight / Hamming Distance Algorithms

Here are the posts related to Hamming Distance (XOR, The number of different bits):

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
460 words
Last Post: Teaching Kids Programming - K Numbers Greater Than or Equal to K using Binary Search
Next Post: Teaching Kids Programming - Insert a Node into a Binary Search Tree via Recursion

The Permanent URL is: GoLang: Compute the Hamming Distance

Leave a Reply