LeetCode461. Hamming Distance

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 ≤ xy < 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.

字符串的汉明距离指的是二进制表示时,两个字符串相应位置的不同元素的个数。先通过位操作中的异或获得不同位元素的值,然后计算该值中包含的'1'的个数。

https://github.com/abesft/leetcode/blob/master/461HammingDistance/461HammingDistance.cpp

#include <iostream>


//https://en.wikipedia.org/wiki/Hamming_distance
class Solution {
public:
	int hammingDistance(int x, int y) {
		int dist = 0;
		unsigned  val = x ^ y;

		// Count the number of bits set
		while (val != 0)
		{
			// A bit is set, so increment the count and clear the bit
			dist++;
			val &= val - 1;
		}

		// Return the number of differing bits
		return dist;
	}
};

int main()
{
	Solution sln;
	std::cout << sln.hammingDistance(1, 4) << std::endl;
	std::cout << "Hello World!\n";
}

猜你喜欢

转载自blog.csdn.net/grllery/article/details/85270110