[leetcode: Python]461. Hamming Distance
来源:互联网 发布:腾讯社交网络算法大赛 编辑:程序博客网 时间:2024/06/06 11:36
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 < 231.
Example:
Input: x = 1, y = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑
The above arrows point to positions where the corresponding bits are different.
题目大意:
两个整数的汉明距离是指其二进制不相等的位的个数。
给定两个整数x和y,计算汉明距离。
注意:
0 ≤ x, y < 2^31.
解题思路:
异或运算
方法一:56ms
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x1 = bin(x)[2:] x2 = x1.zfill(32) y1 = bin(y)[2:] y2 = y1.zfill(32) h = 0 for i in range(32): if x2[i] != y2[i]: h += 1 return h
方法二:39ms
异或运算
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count('1')
阅读全文
0 0
- LeetCode 461. Hamming Distance-python
- [leetcode]461. Hamming Distance --python
- [leetcode: Python]461. Hamming Distance
- LeetCode 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- LeetCode 461. Hamming Distance
- LeetCode - 461. Hamming Distance
- LeetCode-461. Hamming Distance
- 【LeetCode】 461. Hamming Distance
- Leetcode-461. Hamming Distance
- Leetcode 461. Hamming Distance
- LeetCode--461. Hamming Distance
- 461. Hamming Distance [LeetCode]
- [LeetCode]461. Hamming Distance
- leetcode 461. Hamming Distance
- Leetcode 461. Hamming Distance
- LeetCode 461. Hamming Distance
- 【LeetCode】461. Hamming Distance
- 构造函数的作用
- SVN在Android Studio中的配置(五)
- Linux-内存管理机制、内存监控、buffer/cache异同
- springMVC系列(二)——两种搭建方式
- java之继承、多态、抽象类
- [leetcode: Python]461. Hamming Distance
- MD5防止数据被篡改的做法
- ttr()、counter()和calc()在css中的使用
- picasso实现下载圆形图片
- jquery文件上传控件 Uploadify
- The Lab Render (Valve开源VR渲染优化插件)
- Windows中VS_VERSION_INFO详解
- 界面技术<一>
- bzoj 1115阶梯博弈