461. Hamming Distance

移位法,用1作为mask后异或算出个数。

public int hammingDistance(int x, int y) {
    int res = 0;
    while (x != 0 || y != 0) {
        res += (x & 1) ^ (y & 1);
        x >>>= 1;
        y >>>= 1;
    }
    return res;
}

调库

return Integer.bitCount(x ^ y);

results matching ""

    No results matching ""