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 ≤ 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

posted @ 2020-04-01 01:01  littledy  阅读(83)  评论(0编辑  收藏  举报