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 usingfmt.Sprintf()with"%b. - Count and return the number of
1s in the string, usingstrings.Count().
import (
"fmt"
"strings"
)
func ΗammingDistance(n, m int) int {
return strings.Count(fmt.Sprintf("%b", n^m), "1")
}ΗammingDistance(2, 3) // 1