【LeetCode】461. Hamming Distance (java实现)

原题链接

https://leetcode.com/problems/hamming-distance/

原题

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 ≤ x, y < 231.

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.

题目要求

“汉明距离”,一个较为著名的问题,给定两个整数,求出这两个数字的二进制中位数不同的个数。比如上面的1和4,在第0位和第2位数字不同,因此这个汉明距离就是2。

解法

解法一:分别列出两个数字的二进制形式,并放在两个数组中,数组的索引级二进制形式中的位数,元素值即位数上对应的值。逐个的比较元素值,从而得出结果。这种方法直白,容易想到,但总感觉效率低下,不那么“高级”,这里我就不列出具体代码了。
解法二:比较两个二进制数字中不一样的数据,其实可以直接将两个数字取异或,然后再求出异或结果的二进制形式中有多少个1即可。

int hammingDistance(int x, int y) {
    int i = x ^ y;
    int count=0;
    while (i != 0) {
        ++ count;
        i = (i-1)& i;
    }
    return count;
}    

注意:求出数字的二进制形式中有多少个1,有多种方法,详情参见:http://www.xuebuyuan.com/1416450.html?mobile=1

测试用例:

    public static void main(String[] args) {
        Solution s = new Solution();
        assert(s.hammingDistance(1, 4) == 2);
        assert(s.hammingDistance(1, 0) == 1);
        assert(s.hammingDistance(1, 1) == 0);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值