题目描述:
The 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 = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different. 解题思路: 题目不难,直接上代码。 代码:
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 int num = 0; 5 int tmp = x xor y; 6 while (tmp != 0) { 7 if (tmp % 2) 8 num ++; 9 tmp /= 2;10 }11 return num;12 }13 };