1. 程式人生 > >LeetCode題解:Hamming Distance

LeetCode題解:Hamming Distance

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.

思路:

先通過異或得到不同的位,然後計數。

題解:

int hammingDistance(int x, int y) {
    int v = x ^ y;
    int nbits(0);
    while(v) {
        if (v & 1) {
            ++nbits;
        }
        v >>= 1;
    }
    return nbits;
}