int CountBit(int x){
int ret = 0;
while(x){
ret++;
x &= x-1; // 等价于 x = x & (x-1)
}
return ret;
}
原理: 把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0。
int CountBit(int x){
int ret = 0;
while(x){
ret++;
x &= x-1; // 等价于 x = x & (x-1)
}
return ret;
}
原理: 把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0。