二进制数中1的个数
n = n&(n - 1);
每次n中少一个1;
用一个while+计数器count来记录
int Fine(int n)
{
int count = 0;
while (n)
{
n = n&(n - 1);
count++;
}
return count;
}
整数m和n的二进制表达中,有多少个位(bit)不同
用上面的方法计算1的不同,首先要用^异或出n和m中的不同位全部变为1;
int Func(int m, int n)
{
int tmp = m^n;
int count = 0;
while (tmp != 0)
{
count++;
tmp = tmp&(tmp - 1);
}
return count;
}
int main()
{
printf("%d\n", Func(1999, 2299));
return 0;
}```