461. Hamming distance (Hamming Distance) leetcode

First attach topic Link:  https://leetcode-cn.com/problems/hamming-distance/

A: Title

     Hamming distance between two integers refers to two figures corresponding to the number of different bit positions. Given two integers x and y, the calculation of the Hamming distance between them.

      Note: 0 ≤ X, Y <231.

Example:

Input: x = 1, y = 4

Output: 2

Explain:
. 1 (0 0 0. 1)
. 4 (0. 1 0 0)
↑ ↑

The above stated different arrows corresponding to the bit position.

  Brief Description : Here is to us the sum of two corresponding binary number, how many positions 1 is a single, separate meaning here refers to the number two position is a (0,1) in the form, then this 1 It is separate.

         It is to be noted that the x, y range, so we just need a variable int on the line.

II: Method (c ++)

  1: Method a: direct shift, each taking two last bit judgment

    This binary problem, the first thought is that we can not or will shift and, or, and other operations. Here the last number of each comparison, if a 0, a is 1 count.

   int count=0;
        while(x!=0||y!=0)
        {
            if((x&1)!=(y&1))
            {
                count++;
            }
            x>>=1;
            y>>=1;
        }
        return count ;

  2: Method two: Weight Jiahan Ming Hamming distance

    Here we first need to introduce these two concepts. Hamming Weight : Number 1 in a binary number.   Hamming distance : the number of different bit positions (as said subject, corresponding to a number of different locations).

    Hamming Weight : n = n & (n- 1)

      6 as an example here for: 0110

      First; 0110 & 0101 = 0100: 1 to remove the last of

      Second: 0100 & 0011 = 000: The last one removed

    Hamming distance : the nature of the two numbers is the exclusive OR of characters "1" number, can be used as exclusive or implemented.

    So here we first calculate the XOR which places different locations 1. Then Hamming weight, which again count the number of binary 1 is derived exclusive OR.

int hammingDistance ( int X, int Y) {
           // Hamming distance plus wt 
        int SUM = X ^ Y; // XOR to determine which are not the same, that will be different to a discriminant out 
        int COUNT = 0 ;
         the while (SUM =! 0 ) 
        { 
            SUM = SUM & sum- . 1 ; // sequentially remove a 
            COUNT ++ ;    
        } 
        return COUNT; 
    }

 

Guess you like

Origin www.cnblogs.com/carrollCN/p/11456606.html