天天看點

461. 漢明距離(位運算)

461. 漢明距離(位運算)

方法一:

使用 Integerl.toBinaryString();

class Solution {
    public int hammingDistance(int x, int y) {
        int c = x^y,cnt = 0;
        String res = Integer.toBinaryString(c);
        System.out.println(res);
        for(int i = 0;i<res.length();i++){
            if(res.charAt(i)=='1')cnt++;
        }
        return cnt;
    }
}
           

方法2:

class Solution {
    public int hammingDistance(int x, int y) {
        int c = x^y,cnt = 0;
        while(c>0){
        //注意,&和 == 的優先級關系,==的優先級 > &
            if((c&1) == 1)cnt++;
            c = c>>1;
        }
        return cnt;
    }
}
           

方法3:

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x^y);
    }
}
           

方法4:

使用 z&(z-1) 去除 z 位級表示最低的那一位。

class Solution {
    public int hammingDistance(int x, int y) {
        int c = x^y,cnt = 0;
        while(c>0){
            c = c&(c-1);
            cnt++;
        }
        return cnt;
    }
}