461. Hamming Distance

题目描述:

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 ≤ xy < 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 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 };

 

posted @ 2018-07-28 21:10  gszzsg  阅读(103)  评论(0编辑  收藏  举报