461. Hamming Distance (Easy)
TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.
Given two integersx
andy
, calculate the Hamming distance.
Note:
0 ≤x
,y
< 2^31.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
Solution 1: Bit Maniulation O(1); O(1)
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int res = 0;
while (xor != 0) {
res += xor & 1;
xor >>>= 1; //因为输入是非负数,所以可以不用无符号右移>>>,用>>即可
}
return res;
}
Solution 2: Bit Maniulation O(1); O(1) 低效,不推荐,但是477要用到这种形式
public int hammingDistance(int x, int y) {
int count = 0;
for (int i = 0; i < 32; i++) {
if (((x % 2) ^ (y % 2)) == 1) { // the modulus is 2 instead of 10.
count++;
}
x >>>= 1; //因为输入是非负数,所以可以不用无符号右移>>>,用>>即可
y >>>= 1;
}
return count;
}