题目链接:
https://leetcode.com/problems/hamming-distance/description/
题目描述:
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.
二进制位不同,自然而然想到了位运算的异或
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
int count = 0;
while (z != 0) {
if (z & 1) count++;
z >>= 1;
}
return count;
}
};
本题主要要求掌握位运算
提交结果: