leetcode_461. Hamming Distance 计算汉明距离,按位异或运算,计算整数的二进制表示中1的个数 java

来源:互联网 发布:两列数据查找相同项 编辑:程序博客网 时间:2024/05/18 21:05

题目:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.

题意:

给定两个整数x,y,计算x和y的汉明距离。汉明距离是指x、y的二进制表示中,相同位置上数字不相同的所有情况数。


代码:

public class Solution {
    public int hammingDistance(int x, int y) {
        int z = x^y;              #先将x,y按位异或运算,得到不相同位置上为1的整数z
        int res = 0;
        while(z != 0) {            #计算整数z的二进制中1的个数,即为x和y的汉明距离
            if (z%2 == 1) {
                res++;
            }
            z = z/2;
        }
        return res;
    }
}


笔记:

最近都会用java写代码哦。

0 0
原创粉丝点击