【Leetcode】461. Hamming Distance

题目地址:

https://leetcode.com/problems/hamming-distance/

给定两个数,判断其二进制表示对应位有多少位不同的。直接求异或然后算一下有多少个11即可。可以用lowbit来做。代码如下:

public class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int res = 0;
        while (xor != 0) {
            xor -= lowbit(xor);
            res++;
        }
        
        return res;
    }
    
    private int lowbit(int x) {
        return x & -x;
    }
}

时空复杂度O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章