Fork me on GitHub

[leetcode-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 ≤ 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.

思路:

很朴素,就是依次取出最后一位,然后进行比较。

int hammingDistance(int x, int y)
     {
         int res = 0;
         while (x && y)
         {
             int tempx = x & 1;
             int tempy = y & 1;
             if (tempx != tempy)res++;
             x >>= 1;
             y >>= 1;
         }
         while (x)
         {
             int tempx = x & 1;
             x >>= 1;
             if (tempx) res++;
         }
         while (y)
         {
             int tempy = y & 1;
             y >>= 1;
             if (tempy) res++;
         }
         return res;
     }

看到了大神的精简干净的代码,五体投地。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};

 

posted @ 2017-04-28 23:04  hellowOOOrld  阅读(259)  评论(0编辑  收藏  举报