Leet Code 461:汉明距离(位运算)

Leet Code 461:汉明距离

求两个整数二进制位数不同的个数
异或:^ 不同为1,相同为0

快解
int hammingDistance(int x, int y) {
        int xorresult=x^y;
        int count=0;
        while(xorresult!=0)
        {
            xorresult=xorresult&(xorresult-1);
            count++;
        }
        return count;
}
慢解
int hammingDistance(int x, int y) {
        int count=0;
        while(x!=0 || y!=0){
            if((x&1) ^ (y&1)) count++;
            x=x>>1;y=y>>1;
        }
        return count;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章