461. Hamming Distance

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.