计算二进制数中有几个1
while(x != 0) {
x = x & (x-1);
count++;
}
二进制数检测某一位是否为1或者设置为1
int seen = 0
(seen & (1 << x)) == 0
seen |= (1 << x)
二分模板,检索可能存在的最大/小值
// 当r=mid时,mid=l+r>>1
// 当l=mid时,mid=l+r+1>>1
public int maxValue(int n, int index, int maxSum) {
int left = 1, right = maxSum;
while (left < right) {
int mid = (left + right + 1) / 2;
if (valid(mid, n, index, maxSum)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
求解二进制数最低位1
// 防止溢出
int lsb = (xorsum == Integer.MIN_VALUE ? xorsum : xorsum & (-xorsum));
// 3: 0000 0010
// -3: !3 + 1 -> 1111 1110
// 3 & -3 = 0000 0010