Algorithm of "Leetcode" Hamming distance and its application by __ algorithm

Source: Internet
Author: User

1, what is Hamming distance
Hamming distance, from the binary aspect, is two equal long string of binary corresponding bit is not the same number of digits, such as

1011
1000//Hamming distance is 2
1100
1010//Hamming distance is 2

2. Algorithm for calculating Hamming distance

 idea:

01. After the two given number of different or (^) operations stored in the variable A, Hamming distance is a binary 1 of the number of

02. When a is not 0 o'clock, a bitwise AND (&) operation is performed with the 0x01. If the result is 1, then the statistic variable plus 1

03. Move a right one, repeat step No. 02

Code:

Class Solution {public 
  :
     int hammingdistance (int x, int y) {
        int cnt = 0;
        X=x^y;
        while (x!=0)
        {
            if (x&0x01)
              cnt++;
        x=x>>1;
     }
       return cnt;         
    }
 ;

  

If written in Python, ^ in Python refers to "bitwise XOR": When two corresponding binary differences, the result is 1

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.