【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 positionsat 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 = 4Output: 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】Linked List Cycle 解题报告(Java & Python)
- 【LeetCode】Binary Tree Paths 解题报告(java & python)
- 【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)
- 【LeetCode】Reverse Linked List 解题报告(Python & java)
- 【LeetCode】Single Number 解题报告(Java & Python)
- 【LeetCode】Two Sum 解题报告(java & python)
- 【LeetCode】Group Anagrams 解题报告(Python & Java)
- 【LeetCode】Merge Two Sorted Lists 解题报告(Java & Python)
- 【剑指Offer】从尾到头打印链表 解题报告(java & python)
- 【剑指Offer】重建二叉树 解题报告(Java & Python)
- Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
- 【剑指Offer】二维数组中的查找 解题报告(Java & Python)
- Leetcode 494 python 解题报告
- Leetcode 459 python 解题报告
- LeetCode 227. Basic Calculator II 解题报告【python】
- Leetcode 486 python 解题报告
- Ugly Number | leetcode 263 【Java解题报告】
- Maximum Depth of Binary Tree | leetcode 104 【Java解题报告】
- leetcode 416 python 解题报告
- Add Binary | leetcode 67 【Java解题报告】