LeetCode-探索-初级算法-其他-2. 汉明距离(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 汉明距离
-
语言:java
-
思路:先异或运算,那么就转换成“位1的个数”问题了。
-
代码(0ms):
class Solution { public int hammingDistance(int x, int y) { int tmp = x ^ y; int res = 0; while(tmp>0){ ++res; tmp &= (tmp-1); } return res; } } -
参考代码(0ms):调用java原本就有的统计二进制数1的个数的方法
class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x^y); } }

本文详细介绍了如何使用Java实现LeetCode初级算法中的汉明距离计算。通过异或运算和位操作,高效地统计两个整数间不同的二进制位数。提供了一种0ms运行时间的解决方案,并对比了两种实现方式。
482

被折叠的 条评论
为什么被折叠?



