原题:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
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.
题意:
简而言之,即是求出两个数转化为二进制数后同一位置上数字不同的个数。
思路:
使用异或运算对两数进行异或操作,之后计算出1的个数即可。
代码:
public class Solution {
public int hammingDistance(int x, int y) {
//计算异或之后1所出现的次数
int t = x ^ y;
int count = 0;
while(t != 0){
if(t % 2 == 1){
count++;
}
t /= 2;
}
return count;
}
}