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
< 231.
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.
This problem allows me to find the Hamming distance between two numbers, the topic explained very clearly, the Hamming distance between the two numbers is the number of the corresponding bits of the second binary number, then the most direct when the practice is to take the number of digits corresponding to two number and different or, we know the nature of the difference or the same 0, the difference is 1, All we have to do is add up to 1 as the Hamming distance, see the code below:
Solution One:
classSolution { Public: intHammingdistance (intXinty) {intres =0; for(inti =0; I < +; ++i) {if((X & (1<< i) ^ (Y & (1<<i )) {++Res; } } returnRes; }};
We can optimize the above code, we can start directly to the two number of different or up, then we traverse the XOR result of each bit, count to 1 number, also can achieve the same effect, see the code is as follows:
Solution Two:
class Solution {public: int hammingdistance (intint y) { int 0, exc = x ^ y; for (int0; + +i) { 1; } return res; };
Let's look at a recursive notation, which is very concise, and the condition of recursive termination is that when two numbers are different or 0 o'clock, it indicates that two numbers are exactly the same at this point, we return 0, otherwise we return XOR and 2 X/2 plus a recursive result for the call to the Y/2 and the. XOR and 2 are equivalent to checking that the lowest bit is the same, whereas recursion on X/2 and Y/2 is equivalent to moving x and Y to the right by one bit, so that each bit can be compared to and get the correct result, see the code below:
Solution Three:
class Solution {public: int hammingdistance (intint y) { if 0 return 0 ; return 2 2 2 ); }};
Resources:
Https://discuss.leetcode.com/topic/72089/java-3-line-solution
Https://discuss.leetcode.com/topic/72093/java-1-line-solution-d
Https://discuss.leetcode.com/topic/72289/0ms-c-two-line-solution
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Hamming Distance Hamming distance