This is a creation in Article, where the information may have evolved or changed.
Problem description
461. Hamming Distance
That is, the number of binary corresponding digits of two positive integers is different.
Principle explanation
In terms of the problem description, the most intuitive solution is that the decimal number is first turned into binary, and then the same number is the same, different counters accumulate, the value of the final counter is Hamming Distance .
Optimization scheme: First ^ operation, the number of bits of the result of the operation to traverse, 1 the counter accumulated
Based on this idea, there is a need to use the 异或运算 and 位运算 .
Xor ^ and XOR or non-
XOR algorithm: The same is zero, the difference is one.
XOR algorithm: The same as one, the difference is zero.
That
输入A: 1 0 1 0输入B: 1 1 0 0异或运算结果: 0 1 1 0异或非(同或)运算结果:1 0 0 1
Move left << and right >>
Move left
- The right-hand vacated bits are filled with 0
- High-left-shift overflow discards the high
Move right
- The left vacated bits are filled with 0 or 1. Positive numbers are filled with 0, negative numbers are filled with 1
- The low-right-shift overflow discards the bit
Code implementation
func hammingDistance(x int, y int) int { counter := 0 tmp := x ^ y t := 1 for i := uint(0); i < 32 && t > 0; i++ { t = tmp >> i counter += (tmp >> i) & 1 } return counter}
Reference
- Baidu Wikipedia or not
- Baidu Encyclopedia Bit arithmetic