对于一个字节(8bit)的变量,求二进制中1的个数。
//模除法
int first(int a)
{
int count = 0;
while(a)
{
count += a%2;
a /= 2;
}
return count;
}
//右移 &1
int second(int a)
{
int count = 0;
while(a)
{
count += a&0x01;
a>>=1;
}
return count;
}
//
int third(int a)
{
int count = 0;
while(a)
{
a &= a-1;
count++;
}
return count;
}
void main()
{
int a = 9;
int b = 20;
int count = 0;
int n1 = a-(a&(a-1));
int n2 = b-(b&(b-1));
while(n1!=0 && n2!=0)
{
if(n1 == n2)
{
a &= ~n1;
b &= ~n2;
n1 = a-(a&(a-1));
n2 = b-(b&(b-1));
}
else
{
count++;
if(n1 > n2)
{
b &= ~n2;
n2 = b-(b&(b-1));
}
else
{
a &= ~n1;
n1 = a-(a&(a-1));
}
}
}
if(n1 != 0)
{
count++;
a &= ~n1;
n1 = a-(a&(a-1));
}
if(n2 != 0)
{
count++;
b &= ~n2;
n2 = b-(b&(b-1));
}
cout<<"count= "<<count<<endl;
}
/*
void main()
{
int a=9,b=20;
int c = a&b;
int d = a|b;
int e = c^d;
int count = 0;
while(e)
{
e &= e-1;
count++;
}
cout<<count<<endl;
}