您的位置:首页 > 编程语言

Leetcode代码学习周记——Hamming Distance

2017-12-10 21:49 351 查看
题目链接:
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;
}
};

本题主要要求掌握位运算
提交结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: