[LeetCode] 461. Hamming Distance

Problem:

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 = 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.


Solution 1:

(傻瓜法:把两个十进制数转化为二进制串,为了比较各个位是否相同,需要对较短的字符串补"0")

class Solution {
public:
    int hammingDistance(int x, int y) {
        string num1 = convertToBinary(x);
        string num2 = convertToBinary(y);
        return countDifferentBits(num1, num2);
    }
    
    string convertToBinary(int num) {
        string str = "";
        for (int i = num; i > 0; i /= 2) {
            str += ((i % 2) ? '1' : '0');
        }
        reverse(str.begin(), str.end());
        return str;
    }

    void modifyString(string& s, int n) {
	    string str = "";
	    for (int i = 0; i < n; i++) {
		    str += "0";
	    }
	    for (int i = 0; i < s.length(); i++) {
		    str += s[i];
	    }
	    s = str;
    }
    
    int countDifferentBits(string num1, string num2) {
        int count = 0;
        int len1 = num1.length();
        int len2 = num2.length();
        if (len1 < len2) modifyString(num1, len2-len1);
        if (len2 < len1) modifyString(num2, len1-len2);
        for (int i = 0; i < num1.length(); i++) {
            if (num1[i] != num2[i]) {
                count++;
            }
        }
        return count;
    }
};


Solution 2:

(利用异或操作:两个数作异或,相同的位则为0,不同则为1,得到的结果转化为二进制串,计算字符"1"的数目,即为所求

的海明距离)

class Solution {
public:
    int hammingDistance(int x, int y) {
        int z = x ^ y;
        string str = convertToBinary(z);
        return countDifferentBits(str);
    }
    
    // 把十进制数转化成二进制字符串
    string convertToBinary(int num) {
        string str = "";
        for (int i = num; i > 0; i /= 2) {
            str += ((i % 2) ? '1' : '0');
        }
        reverse(str.begin(), str.end());
        return str;
    }

    // 计算海明距离
    int countDifferentBits(string num) {
        int count = 0;
        for (int i = 0; i < num.length(); i++) {
            if (num[i] == '1') {
                count++;
            }
        }
        return count;
    }
};


Solution 3 :

(解法出自:https://discuss.leetcode.com/topic/72236/my-c-solution-using-bit-manipulation

(利用位运算:异或 + 与;首先求得两个数的异或,再通过与运算来计算海明距离)

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};
Note:这里理解n &= n-1是一个难点,这个式子的作用是把n最右边的1转化为0,以此来统计异或结果中1的数目,即海明距离。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值