LeetCode[461]Hamming Distance

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/khy19940520/article/details/78044387
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 = 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.

可运行代码:

#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,不同为1
	int 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;
        
    }
};




猜你喜欢

转载自blog.csdn.net/khy19940520/article/details/78044387