461. Hamming Distance

Easy
借这道题练习下如何转换二进制和基本的位运算
基本运算的讲解

class Solution {
    public int hammingDistance(int x, int y) {
        int res = 0;
        for (int i = 0; i < 31; i++){
            int bx = x % 2;
            int by = y % 2;
            if (bx != by){
                res++;
            }
            x /= 2;
            y /= 2;
        }
        return res;
    }
}

学一下位运算的异或和左移右移之后就可以用一下下面这个方法:

class Solution {
    public int hammingDistance(int x, int y) {
        //1   (0 0 0 1)
        //4   (0 1 0 0)
        //xoy  0 1 0 1
        //&    0 0 0 1 
        //     0 0 0 1
        //xoy >> 1
        //xoy  0 0 0 0
        //&    0 0 0 1
        //     0 0 0 1 
        // check if the last bit of xoy equals to 1 everytime, if yes count increment by 1
        // then shift right xoy to check the next bit, repeat until xoy == 0
        int res = 0;
        int xoy = x ^ y;
        while (xoy != 0){
            res += xoy & 1;
            xoy >>= 1;
        }
        return res;
    }
}

你可能感兴趣的:(461. Hamming Distance)