461. 汉明距离

461. 汉明距离

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 x 和 y,计算它们之间的汉明距离。

注意:
0 ≤ x, y < 231.

示例:

  输入: x = 1, y = 4

  输出: 2

解释:
1 (0 0 0 1)
4 (0 1 0 0)
       ↑    ↑

 

代码:

#include<iostream>
#include<bits/stdc++.h>
#include<cstring>
#include<vector>
using namespace std;
int main(){
    int x,y,sum=0;
    cin>>x>>y;
    while(x>0||y>0){
        if ((x&1)&&!(y&1))
        {
            sum++;
        }else if (!(x&1)&&(y&1))
        {
            sum++;
        }
        x>>=1;
        y>>=1;
        // cout<<"x="<<x<<" y="<<y<<endl;
    }
    cout<<sum<<endl;
}

 

int hammingDistance(int x, int y) {
    int  n = x ^ y, count = 0;
    while(n)
    {
        cout<<"n="<<n<<endl;
        n &= n-1;
        count++;
    }
    return count;
}

 

posted @ 2020-08-22 17:30  多发Paper哈  阅读(63)  评论(0编辑  收藏  举报
Live2D