LeetCode[461]Hamming Distance

来源:互联网 发布:caffe deploy.proto 编辑:程序博客网 时间:2024/06/05 18:53
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.

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.

可运行代码:

#include<iostream>using namespace std;/*解题思路:首先计算x^y,这样不同为1,相同为0,然后再查结果中1的个数查的方法是结果与1进行&运算,累加求和,然后再向右移位。*/int hammingDistance(int x, int y);int main(){int x = 1;int y = 4;int counts;counts = hammingDistance(x, y);cout << counts << endl;system("pause");return 0;}int hammingDistance(int x, int y){int z = 0;z = x^y;//相同为0,不同为1int counts = 0;int tmp;while (z != 0){tmp = z & 1;counts = counts + tmp;z = z >> 1;}return counts;}

提交代码:

class Solution {public:    int hammingDistance(int x, int y)     {        int z=0;        z = x^y;//相同为0,不同为1        int counts = 0;        int tmp = 0;        while(z!=0)        {            tmp = z&1;            counts = counts+tmp;            z = z>>1;        }        return counts;            }};




原创粉丝点击