一、汉明距离
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的数量即可
反思:我最开始做这道题时,直接return(X^Y),最后结果显然不对,应当返回x^y最后得到二进制数字中1的数量。我的思路是先把两个数进行异或运算,之后按照除2取余得到最后一位的数字,如果为1,计数变量加一,如果为0,右移一位,循环进行,直到最后数字为0,操作结束。
代码如下:
class Solution { public: int hammingDistance(int x, int y) { int z=x^y,count=0; while(z!=0) { if(z%2==1) count++; z = z>>1; } return count; } };