首页 > 其他 > 详细

461. Hamming Distance

时间:2020-04-01 11:24:54      阅读:53      评论:0      收藏:0      [点我收藏+]

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 ≤ x, y < 2^{31}\).

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

思路

Solution (C++):

int hammingDistance(int x, int y) {
    vector<int> v1 = getBinary(x), v2 = getBinary(y);
    int m = v1.size(), n = v2.size(), distance = 0;
    while (n > m) {
        v1.push_back(0);
        m++;
    }
    while (m > n) {
        v2.push_back(0);
        n++;
    }
    for (int i = 0; i < m; ++i) {
        if (v1[i] ^ v2[i])  distance++;
    }
    return distance;
}
vector<int> getBinary(int x) {
    vector<int> v{};
    if (x == 0) { v.push_back(0); return v; }
    while (x) {
        v.push_back(x%2);
        x /= 2;
    }
    return v;
}

性能

Runtime: 0 ms??Memory Usage: 6.3 MB

思路

直接考虑按位异或。判断大数在2的多少幂之间可以求出对应的2进制位数。

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

461. Hamming Distance

原文:https://www.cnblogs.com/dysjtu1995/p/12609988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!