83. The algorithm is simple and swift Hamming distance

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.

solution:

   func hammingDistance(_ x: Int, _ y: Int) -> Int {
      /*  先将两个数异或运算得到n,那么n里面1的个数就是结果,如果n不为0,那么n至少有一位是1。如果n减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1。其余所有位将不会受到影响。这样右边这部分的&运算结果就为0,然后循环*/
        
        var n = x ^ y;
        var count = 0;
        while(n != 0){
            count += 1
            n = n & (n-1);
        }
        return count

    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93459934