/*
* Leetcode461. Hamming Distance
* Funtion: 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. 0 ≤ x, y < 2^31.
* Example: Input: x = 1, y = 4 Output: 2
* Author: LKJ
* Date: 2017/2/27
* Hint: 汉明距离,找出不相同的比特数有几个
*/
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x^y;
int result = 0;
while(z){
if(z & 1){
result++;
}
z = z >> 1;
}
return result;
}
};
int main(){
int myin1 = 2;
int myin2 = 4;
int myout;
Solution SA;
myout = SA.hammingDistance(myin1,myin2);
cout << myout << endl;
return 0;
}
LeetCode 简单操作 | 461. Hamming Distance
最新推荐文章于 2024-07-19 19:25:43 发布