LeetCode——Hamming Distance
来源:互联网 发布:韩国工业 知乎 编辑:程序博客网 时间:2024/05/17 02:49
LeetCode—Hamming Distance
开始刷LeetCode,自己实现并进行改正,并学习其他更优解。
#461
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 = 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.
这道题的目的就是要求两个数字之间的汉明距离。两个数字之间的汉明距离就是两个数字二进制下对应位不同的个数。
思路就是将两个数字的二进制进行异或,不同的位数得到1,将1累加起来就是两个数字的汉明距离。
- Python
class Solution(object): def hammingDistance(self, x, y): return bin(x^y).count("1")
bin函数的作用是将x^y的异或结果二进制数转换为字符串,然后count统计其中1的次数。就能够得到两个数的Hamming Distance。
- Java
class Solution{ public int hammingDistance(int x, int y) { int xor = x ^ y,count = 0; for (int i = 0;i < 32;i++) count += (xor >> i) & 1; return count; }
将两位数的异或的二进制结果分别与1进行&,统计结果,并将二进制右移i位。
- C++
看了各位大神,c++有多种答案,记录下方便学习。
class Solution{ public: int hammingDistance(int x,int y) { int res = 0; for (int i = 0;i < 32;i++) { if ((x & (1 << i)) ^ (y & (1 << i))) { ++res; } } return res; } }
两个数字的二进制各位分别与1&,结果进行异或,记录1的次数。这样分别操作比较麻烦,将两个二进制数异或,再遍历结果的每一位。
class Solution{ public: int hammingDistance(int x,int y){ int res = 0,xor = x ^ y; for(int i = 0;i < 32;i++){ res += (xor >> i) & 1; } return res; } };
还有一种递归的方法,也很简洁明了。
class Solution{public: int hammingDistance(int x,int y){ if ((x ^ y) == 0) return 0; return (x ^ y) % 2 + hammingDistance(x / 2, y / 2); }};
还看到一种做法,很巧妙很高效,将两个数进行异或,通过num&(num-1)移除位数位1,这样就不需要处理所有位数。代码如下:
class Solution{public: int hammingDistance(int x,int y){ int res = 0,xor = x ^ y; while (xor) { ++res; xor &= (xor - 1); } return res; }};
上面的xor只是表示是异或,在实际程序中要换个变量名。
- LeetCode——Hamming Distance
- LeetCode——Hamming Distance
- LeetCode——Hamming Distance
- Leetcode学习(4)—— Hamming Distance
- LeetCode——461. Hamming Distance(C++,模拟)
- LeetCode算法题——Total Hamming Distance
- 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
- vs2015配置opencv3.2后又换opencv3.3出现的C4996问题
- 缓存
- 【树形DP】51Nod 1500 苹果曼和树
- TreeMap
- 数据结构--双向约瑟夫
- LeetCode——Hamming Distance
- 设计模式之适配器模式(Adapter):类适配器、对象适配器
- Java 通过JDBC进行数据操作(增删改查)
- 魔漫相机面试心得
- 物理层——计算机网络原理(三)
- Android Gradle学习记录6 代码记录(持续补充)
- XRecycleView的下拉,多条目加载
- 数据库优化
- 网络共享服务FTP