题目来源:
题目描述:
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.
Subscribe to see which companies asked this question.
class Solution {
public:
int hammingDistance(int x, int y) {
int ret=0;
while(x>0 || y>0)
{
if(x%2 != y%2)
ret++;
x/=2;
y/=2;
}
return ret;
}
};
思考:
这是一道很简单的leetcode题目.两个数的汉明距离即是他们转换成二进制后不同的比特位的数量.,想到这一层就很好解决了,通过模二求余的方式即可得到从低到高的每一位比特位的值,每次比较两个数模二的余数是否相同,不同则汉明距离自增1,把两个数都除到0即可得到他们的全部二进制表示.
此题的解法还可以作为转换二进制的方法,只是需要多一个栈来存储每次中间过程的结果即可