力扣【461】汉明距离

题目:

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 x 和 y,计算它们之间的汉明距离。

注意:
0 ≤ x, y < 231.

示例:

输入: x = 1, y = 4

输出: 2

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

上面的箭头指出了对应二进制位不同的位置。

题解:

import java.util.*;

class Solution {
    public int hammingDistance(int x, int y) {
        int res = x ^ y;
        int count = 0;
        while (res != 0) {
            res = res & (res - 1);
            count++;
        }
        return count;
    }
}
public class Main {
    public static void main(String[] args) {
        int x = 1, y = 4;
        Solution solution = new Solution();
        int res = solution.hammingDistance(x, y);
        System.out.println("结果:" + res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq1922631820/article/details/112125697