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); } }