题目地址:
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;
}
}
时空复杂度。