# 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.

class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
for (int i = 0; i < 32; ++i) {
if ((x & (1 << i)) ^ (y & (1 << i))) {
++res;
}
}
return res;
}
};

class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
for (int i = 0; i < 32; ++i) {
res += (exc >> i) & 1;
}
return res;
}
};

class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
while (exc) {
++res;
exc &= (exc - 1);
}
return res;
}
};

class Solution {
public:
int hammingDistance(int x, int y) {
if ((x ^ y) == 0) return 0;
return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
}
};

• 本文已收录于以下专栏：

## 汉明距离（Hamming distance）

• lgfun
• 2016年09月09日 11:51
• 3667

## 【LeetCode】461. Hamming Distance （java实现）

• styshoo
• 2017年01月05日 22:51
• 2855

## Hamming Distance

The Hamming distance between two integers is the number of positions at which the creesponding bits ...

## Leetcode Total Hamming Distance 477

The Hamming distance between two integers is the number of positions at which the corresponding bits...

## HUST 1404 Hamming Distance

Description Have you ever heard of the Hamming distance. It is the number of positions for which ...

## 对tomcat来说，每一个进来的请求(request)都需要一个线程，直到该请求结束。

举报原因： 您举报文章：Hamming Distance 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)