LeetCode-探索-初级算法-其他-2. 汉明距离(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-其他-2. 汉明距离(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 汉明距离
  • 语言: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);
        }
    }
    
发布了60 篇原创文章 · 获赞 6 · 访问量 5516

猜你喜欢

转载自blog.csdn.net/Ashiamd/article/details/102729201
今日推荐