TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.

Given two integersxandy, calculate the Hamming distance.

Note:
0 ≤x,y< 231.

class Solution {
    public int hammingDistance(int x, int y) {
        int n = x ^ y;
        int res = 0;

        for(int i = 0; i < 32; i++) {
            if(((n >> i) & 1) == 1)
                res++;
        }

        return res;
    }
}

results matching ""

    No results matching ""