力扣练习之汉明距离

我爱海鲸 2022-10-10 21:44:27 初级算法

简介初级算法、其他

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnyode/

解法一:

class Solution {
    public int hammingDistance(int x, int y) {
        int tmp = x^y;
        int count = 0;
        if (tmp > 0) {
            while (tmp != 0) {
                count += tmp & 1;
                tmp = tmp >> 1;
            }
        }
        return count;
    }
}

思路:此题的思路与 力扣练习之位1的个数

是一样的,唯一的区别就是将这两个数先进行异或处理,,然后在计算1出现的次数。

你好:我的2025