461. Hamming Distance (python + java)

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.

代码:
python

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count('1')

补知识:
1、Python内置函数:bin()、oct()、int()、hex()分别可以将integer number转化为二、八、十、十六进制的string,且分别带有0b、0o、0x前缀。这用 bin(10)[2:] 可以得到除前辍后的字符串。通过嵌套使用可以做进制之间的转化,例如 bin(int(oct(10))) 可以将十进制的10转化为八进制的数,然后再转十进制的数,最后转二进制的数,这里不用去掉前辍,但是最后print出来的会带有二进制的前缀。
2、python内置函数:str.count(sub, start= 0,end=len(string)) ,sub是子字符串,可以计算得到子字符串出现的数目。

java

public class Solution {
    public int hammingDistance(int x, int y) {
        int sum = 0;
        for(int i = 0; i < 32; i++) {
            int bitx = (x >> i) & 1;
            int bity = (y >> i) & 1;
            sum += (bitx + bity) & 1;
        }
        return sum;
    }
}
public class Solution {
    public int hammingDistance(int x, int y) {

        int z = x ^ y;
        int cnt = 0;

        while(z != 0){
            if((z & 1) == 1){
                cnt ++;
            }
            z = z >> 1;
        }
        return cnt;

    }
}

参考资料:
1、http://www.jb51.net/article/32927.htm 2017.8.3
2、http://www.runoob.com/python/att-string-count.html 2017.8.3
3、http://www.xuebuyuan.com/1416450.html?mobile=1 2017.8.3

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值