原题:
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.
给两个数写成2进制,看看有多少个数不同。随便找了个easy的。
代码:
int hammingDistance(int x, int y) {
int result=x^y;
int n=0;
while(result!=0)
{
if(result%2==1)
n++;
result=result/2;
}
return n;
}
效率不是最佳,但是写的简单。