The Hamming distance between and integers is the number of positions at which, the corresponding bits is different.
Given integers x
y
and, calculate the Hamming distance.
Note:
0≤ x
, y
< 2^31.
Example:
input:x = 1, y = 4output:2explanation:1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑the above arrows point to positions wher e The corresponding bits is different.
Analysis: The idea is to change two numbers into binary, then a single comparison, the same location different words Hamming distance +1;
The original code is as follows:
1 classSolution {2 Public:3 intHammingdistance (intXinty) {4 intdis =0;5 while(x &&y) {6Dis + = (x &1) ^ (Y &1);//x&1 xor y&17X >>=1;//x move right One8Y >>=1;9 }Ten while(x) { OneDis + = (x &1); AX >>=1; - } - while(y) { theDis + = (Y &1); -Y >>=1; - } - returndis; + } -};
Two number is not 0, compare two number of the last, x&1 get x corresponding to the last of the binary, through the XOR operation to determine whether the last one is the same, different plus 1, Same plus 0. After the end of the loop, only one number is not 0, the other number is 0, and at this point 0 corresponds to all the binary is 0, at this time as long as the number of the calculation is not 0 of binary 1 of the number.
Improvement: The above uses three while, with one is enough:
1 classSolution {2 Public:3 intHammingdistance (intXinty) {4 intdis =0;5 while(x | |y) {//or operation, as long as there is a not 0 for this loop6Dis + = (x &1) ^ (Y &1);7X >>=1;8Y >>=1;9 }Ten returndis; One } A};
Improvement: Obviously, as long as the x and Y are different or, the number corresponding to the bits 1 is the Hamming distance of x and Y.
1 classSolution {2 Public:3 intHammingdistance (intXinty) {4 intCount =0;5 intt = x ^y;6 while(t) {7Count + = t &1;8T >>=1;9 }Ten returncount; One } A};
461. Hamming Distance