題目地址:
https://leetcode.com/problems/hamming-distance/
給定兩個數,判斷其二進制表示對應位有多少位不同的。直接求異或然後算一下有多少個即可。可以用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;
}
}
時空複雜度。