Han Ming endless distance algorithm

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
解释
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above stated different arrows corresponding to the bit position.

answer:

Standard Solution:

class Solution {
    public int hammingDistance(int x, int y) {
        int result=x^y; // 异或运算
        int count =0; 
        while(result!=0){  // 如果为0 -> 二进制位都为0 没必要继续下去了
            count += result & 1; // 按位与
            result = result >> 1; // 逻辑右移
        }
        return count;
    }
}

Lazy solution:

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x^y);
    }
}
Published 125 original articles · won praise 236 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/103798323