This is a creation in Article, where the information may have evolved or changed.
Title Description
https://leetcode.com/problems/hamming-distance/description/
The Hamming distance between and integers is the number of positions at which, the corresponding bits is different.
Given 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 is different.
Thinking of solving problems
This topic examines the knowledge point is an XOR operator ^, the idea is to solve the problem is the X, y two number of different or operation, and then statistics 1 occurrences.
Related knowledge points
In this topic, the meaning of Hamming distance is two integers of different bits and.
Xor operator is "same as 0, different from 1"
Golang Code
Hammingdistance.go
package _461_HammingDistancefunc 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)}
Test code
Hammingdistance_test.go
package _461_HammingDistanceimport ( "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) }}