461. Hamming Distance
来源:互联网 发布:阻止电脑自动安装软件 编辑:程序博客网 时间:2024/05/21 19:27
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.我的解答:
class Solution {public: int hammingDistance(int x, int y) { int r = x ^ y; int sum = 0; for(int i = 0; i < 8 * sizeof(int); ++i){ int ret = r & (0x1 << i); if(ret){ sum++; } } return sum; }};在leetcode上看到一个解答:
class Solution {public: int hammingDistance(int x, int y) { int dist = 0, n = x ^ y; while (n) { ++dist; n &= n - 1; } return dist; }};注意其中有一个式子: n &= n - 1
看一个例子 n = 100100 n - 1 = 100011
可以看到 n & n - 1 的效果式将n中最后一个1给消掉。这样计算异或后的1的个数的时间复杂度对于1比较少的数字来说比遍历要快不少。
那么看看利用这个性质还可以解决哪些问题。
1.判断n是否是2的幂,或0
如果是2的幂的话,那么其2进制数中只有1位为1,那么如果n不为0且n & n - 1 = 0,则n为2的幂
2.如本题中计算二进制数中1的个数
阅读全文
0 0
- LeetCode 461. Hamming Distance
- 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- 461. Hamming Distance
- LeetCode 461. Hamming Distance
- 461. Hamming Distance
- LeetCode - 461. Hamming Distance
- 461. Hamming Distance*
- LeetCode-461. Hamming Distance
- 461. Hamming Distance
- 【LeetCode】 461. Hamming Distance
- 461. Hamming Distance
- 461. Hamming Distance#1
- 461. Hamming Distance
- Leetcode-461. Hamming Distance
- 461. Hamming Distance
- Leetcode 461. Hamming Distance
- 461. Hamming Distance
- rqnoj 169
- tensorflow学习3--实现自编码器
- HashMap的工作原理
- 用python完成简单面试题
- 第一周周四总结
- 461. Hamming Distance
- Unity_Legacy动画的合成_069
- 在windows下配置anaconda+tensorflow
- 算法题练习系列之(三十一): 统计同成绩学生
- Spring批处理以及事务
- HDU 6180 Schedule(贪心)
- Android应用组件之概览屏幕
- 与原来的我渐行渐远——我的年终总结
- 小米笔试(风口的猪-中国牛市)