LeetCode | 461. Hamming Distance 12_16

来源:互联网 发布:arduino 网络模块 编辑:程序博客网 时间:2024/06/15 10:05

The Hamming distance betweentwo integers is the number of positions at which the corresponding bits aredifferent.

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 correspondingbits are different.

 

水题,但是这题教会了我如何判断一个数字的二进制数里面有多少个1,这种方法记住了

class Solution {

public:

    int hammingDistance(int x, int y) {

       int c = x^y; int count = 0;

      while(c>0)

      {

            if ((c & 1) == 1) count++;

      c >>= 1;

      }

      return count;

    }

};