【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)

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