题目描述
https://leetcode.com/problems/hamming-distance/description/
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.
Note:
0 ≤ x, y< 2^31.
Example:
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.
解题思路
此题考察的是知识点是异或运算符^,解题的思路就是将x,y两数进行异或运算,然后统计1的出现次数。
相关知识点
在本题目中,汉明距离的含义是两个整数的不同二进制位的和。
异或运算符作用为“相同出0,不同出1”
Golang代码
hammingDistance.go
package _461_HammingDistance
func HammingWeight(z int) (w int){
for z > 0 {
tmp := z % 2
if 1 == tmp {
w++
}
z = z /2
}
return w
}
func HammingDistance(x int, y int) int {
z := x ^ y
return HammingWeight(z)
}
测试代码
hammingDistance_test.go
package _461_HammingDistance
import (
"testing"
)
func Test_HammingDistance(t *testing.T) {
ret := HammingDistance(1, 4)
if 2 != ret {
t.Errorf("test fail, want 2, get %+v\n", ret)
} else {
t.Logf("test pass, want 2, get %+v\n", ret)
}
}