# 461. Hamming Distance 汉明距离

@TOC

• Total Accepted: 12155
• Total Submissions: 16696
• Difficulty: Easy

## # 题目描述

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 ≤ x, y < 2^31.

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.

## # 解题方法

### # Java解法

#### # 方法一：异或 + 字符串分割

public class Solution {
public int hammingDistance(int x, int y) {
return Integer.toBinaryString(x ^ y).split("0").length - 1;
}
}

AC:18 ms

#### # 方法二：异或 + 字符串遍历

public class Solution {
public int hammingDistance(int x, int y) {
String charString = Integer.toBinaryString(x ^ y);
for (int i = 0; i < charString.length(); i++) {
if (charString.charAt(i) == '1') {
}
}
}
}

AC:12 ms

#### # 方法三：异或 + 位统计

public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}

### # 二刷 python解法

#### # 方法一：异或 + 字符串count

python 封装的比较好用。

class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')

#### # 方法二：循环异或

class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
res = 0
while x or y:
if (x & 1) ^ (y & 1):
res += 1
x >>= 1
y >>= 1
return res

#### # 方法三：异或 + 单次遍历

class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xor = x ^ y
res = 0
while xor:
res += xor & 1
xor >>= 1
return res

## # 日期

2017 年 1 月 2 日

2018 年 3 月 9 日

2018 年 11 月 2 日 —— 浑浑噩噩的一天