题目:
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.
题意:
给定两个整数x,y,计算x和y的汉明距离。汉明距离是指x、y的二进制表示中,相同位置上数字不相同的所有情况数。
代码:
public class Solution {
public int hammingDistance(int x, int y) {
int z = x^y; #先将x,y按位异或运算,得到不相同位置上为1的整数z
int res = 0;
while(z != 0) { #计算整数z的二进制中1的个数,即为x和y的汉明距离
if (z%2 == 1) {
res++;
}
z = z/2;
}
return res;
}
}
笔记:
最近都会用java写代码哦。