LeetCode 461. Hamming Distance
考点 | 难度 |
---|---|
Bit Manipulation | Easy |
题目
The Hamming distance
between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, return the Hamming distance between them.
思路
用x^y
判断两个bits是不是一样(如果一样是1
,不一样是0
),然后向右移动一位,再判断。
答案
public int hammingDistance(int x, int y) {
int d = 0;
int bitxor = x ^ y;
while (bitxor > 0){
if (bitxor % 2 == 1){
d++;
}
bitxor = bitxor >> 1;
}
return d;
}