Leetcode:Hamming Distance一些小结
来源:互联网 发布:什么是编程范式 编辑:程序博客网 时间:2024/06/10 12:42
首先,复述一遍题目要求:
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 = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different.
我是采用python3来求解,在优化算法时,看到了一一个很有趣的解法:
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ xor = x ^ y count = 0 for _ in range(32): count += xor & 1 xor = xor >> 1 return count
其中,^,&,>>这几个运算符的用法让我耳目一新。参考:http://blog.csdn.net/ialexanderi/article/details/78581621 来进行分析:
x^y将二者二进制转换中,0^1 = 1, 0^0=0, 1^1=0
>>> bin(1)'0b1'>>> bin(4)'0b100'>>> bin(1^4)'0b101'>>>
这样就可以把相同的位数消除。&将二进制‘1’提出。然后二进制xor<<向左整体移动一位,即xor = xor*2,将提出的位数排除。总计的count就是x,y转换成二进制后相同位数上值不同的数量。
阅读全文
0 0
- Leetcode:Hamming Distance一些小结
- LeetCode 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- [LeetCode-461]Hamming Distance
- LeetCode 461. Hamming Distance
- [LeetCode]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 Hamming Distance
- leetcode 461: Hamming Distance
- Leetcode-461. Hamming Distance
- leetcode--461 : Hamming Distance
- Leetcode 477: hamming distance
- Leetcode 461. Hamming Distance
- Java注解(Annotation)详解(一)——概述及JDK自带注解
- Ajax提交form表单(包括文件上传)
- 使用Pandas对数据进行筛选和排序
- Qt之QTcpServer/QTcpSocket简单收发信息(2)
- struts2_day03_16_ognl表达式#使用_17_ognl表达式%使用
- Leetcode:Hamming Distance一些小结
- Mock.js使用
- 共同学习Java源代码-数据结构-HashMap(十八)
- qrcode将生成的二维码转成img格式
- ubuntu 16.04 64bits 交叉编译openssl到arm-linux
- HDU-1698 Just a Hook (线段树 区间修改查询)
- aidl
- 生活随笔
- Failed to read artifact descriptor