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

【LeetCode】Hamming Distance 解题报告(java & python)

2017-01-06 15:23 639 查看

【LeetCode】Hamming Distance 解题报告(java & python)

[LeetCode]

https://leetcode.com/problems/hamming-distance/

Total Accepted: 12155

Total Submissions: 16696

Difficulty: Easy

Question

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.

Ways

位运算,明显的是两者不一样时结果为一,那么就是使用异或。为了统计1的个数废了一点劲。

方法一:

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


AC:18 ms

方法二:

上述方法效率不是很高,所以我试了试用统计1出现的次数的方法。

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


AC:12 ms

方法三:

看了top答案发现我对java的库函数还是不够了解。这个方法太酷了!

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


方法四:

==二刷 python

python 封装的比较好用。

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


Date

2017 年 1 月 2 日

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