一 题目:
二 思路:
位运算,详细直接看代码吧
三 代码:
class Solution {
public int hammingDistance(int x, int y) {
//异或,相同为0,相异为1,那么temp中1的位置就是二进制数不同的地方
int temp=x^y;
//统计temp里1的个数
int res=0;
while (temp!=0){
//&相同为1,不同为0
//判断最后一位是否为1
if ((temp&1)==1){
res++;
}
//右移一位,我们每次仅需要判断最后一位是否为0即可
temp=temp>>1;
}
return 0;
}
}








网友评论