30秒学会 Golang 片段 · 2019年9月14日

30秒学会 Golang 片段 – HammingDistance

Calculates the Hamming distance between two values.

Use the XOR operator (^) to find the bit difference between the two numbersand convert to a binary string using fmt.Sprintf() with "%b.
Count and return the number of 1s in the string, using strings.Count().

代码实现

import (
    "fmt"
    "strings"
)

func ΗammingDistance(n, m int) int {
    return strings.Count(fmt.Sprintf("%b", n^m), "1")
}

使用样例

ΗammingDistance(2, 3) // 1