Leetcode 461. Hamming Distance
Topics
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.
Solution:
Class Solution {public
:
int hammingdistance (int x, int y) {
int z = x^y;
int ans = 0;
while (z) {
ans++;
Z &= z-1;
}
return ans;
}
;
Writing this blog is mainly to record the clever use of Z-&= z-1-bit operations:
n = 10100 (binary), then (n-1) = 10011 = = "n& (n-1) = 10000
You can see that the original lowest bit of 1 is changed to 0. This can be used for the following applications:
1: Determine if a number is 2 operational (only the highest bit in the number of binary binary is 1)
n > 0 && ((N & (n-1)) = = 0)
2: Calculates the binary of a positive integer containing 1 of the number, for example in this code
3: Calculate the number of n! 2 of the mass factor
Easy to draw N. Number of factorization 2 = [N/2] + [N/4] + [N/8] + ....
Here's a simple example to deduce the process: N = 10101 (binary representation)
Now we track the highest bit of 1, regardless of the other bits assumed to be 0,
Then in
[N/2] 01000
[N/4] 00100
[N/8] 00010
[N/8] 00001
Then all add equals 01111 = 10000-1
The other bits are available: (10101)! The number of the mass factor 2 is 10000-1 + 00100-1 + 00001-1 = 10101-3 (the number of 1 in the binary representation)
The number of the mass factor 2 of the generalized n! is N-(the number of 1 in the N binary representation)
[1]n & (N-1)