数据结构与算法:leetcode_461_Hamming Distance

  • Description
    The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 0 ≤ x, y < 2’31.
    Given two integers x and y, calculate the Hamming distance.
  • Example
    Input: x = 1, y = 4
    Output: 2
    Explanation:
    1 (0 0 0 1)
    4 (0 1 0 0)
    ↑ ↑
    The above arrows point to positions where the corresponding bits are different.
  • Solution
public int hammingDistance(int x, int y) {
        int distance = 0;
        int temp = x ^ y;// 获取两个二进制数的不同位数的值;
        while (temp != 0) {
            distance++;
            temp = temp & (temp - 1);//计算一个二进制数中含1的个数
        }
        System.out.println(distance);
        return distance;
    }

猜你喜欢

转载自blog.csdn.net/weixin_38021928/article/details/81149392