leetcode 461

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的个数。统计方法为:循环计算z&(z-1)直到z为0,其实我感觉是一直比较的是最后一位

1.c++做法

class Solution {
public:
    int hammingDistance(int x, int y) {
        int hammingDistance=0;
        int z=x^y;//这是取x 与y的按位异或
        while(z!=0){
           hammingDistance++;
            z=z & (z-1);//这里是取z 与z-1的与
        }
        return hammingDistance;
    }
};
class Solution {
public:
    int hammingDistance(int x, int y) {
        int res = 0, exc = x ^ y;
        for (int i = 0; i < 32; ++i) {
            res += (exc >> i) & 1;//这种做法看起来更直观一点,循环左移,和1相与得到只保留了最后一位的中间结果
        }                                         //判断最后一位是否为1,为1说明距离res+1    
      return res;}};

2.Discuss最优解(java)

public class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

内置函数Integer.bitCount()

/** 
     * Returns the number of one-bits in the two's complement binary 
     * representation of the specified {@code int} value.  This function is 
     * sometimes referred to as the <i>population count</i>. 
     * 
     * @return the number of one-bits in the two's complement binary 
     *     representation of the specified {@code int} value. 
     * @since 1.5 
     */  
    public static int bitCount(int i) {  
        // HD, Figure 5-2  
        i = i - ((i >>> 1) & 0x55555555);  
        i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);  
        i = (i + (i >>> 4)) & 0x0f0f0f0f;  
        i = i + (i >>> 8);  
        i = i + (i >>> 16);  
        return i & 0x3f;  
    }  
二分法,两两一组相加,之后四个四个一组相加,接着八个八个,最后就得到各位之和了。 第一行是计算每两位中的 1 的个数 , 并且用该对应的两位来存储这个个数 , 如 : 01101100 -> 01011000 , 即先把前者每两位分段 01 10 11 00 , 分别有 1 1 2 0 个 1, 用两位二进制数表示为 01 01 10 00, 合起来为 01011000. 第二行是计算每四位中的 1 的个数 , 并且用该对应的四位来存储这个个数 . 如 : 01101100 经过第一行计算后得 01011000 , 然后把 01011000 每四位分段成 0101 1000 , 段内移位相加 : 前段 01+01 =10 , 后段 10+00=10, 分别用四位二进制数表示为 0010 0010, 合起来为 00100010 . 下面的各行以此类推 , 分别计算每 8 位 ,16 位 ,32 位中的 1 的个数 . 将 0x55555555, 0x33333333, 0x0f0f0f0f 写成二进制数的形式就容易明白了 .

3.python做法

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count('1')
总体来看还是python更简洁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值