Leetcode:461. 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, calculate the Hamming distance.

範例:

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.

之前在寫碩論的時候有用到漢明距離
漢明距離可以參考這篇

2數做or找出相異bit之後,計算有幾個相異的bit數就好

func hammingDistance(x int, y int) int {
    sum := x^y
    var count =0
    for {
        if sum==0{
            break
        }
        if sum%2==1{
            count++
        }
        sum/=2
    }
    return count
}
Next PostRead more articles

發佈留言