题目:对于一个字节(8bit)的无符号整型变量,求其二进制表示中 1 的个数,要求算法的执行效率尽可能高。
1、使用模方法
#include<iostream>
using namespacestd;
intCount(unsigned char v)
{
int count = 0;
while(v != 0)
{
if(v % 2 == 1)
count++;
v /= 2;
}
return count;
}
void main()
{
unsigned char ch = 255;
int count = Count(ch);
cout<<"count ="<<count<<endl;
}
2、 使用位操作运算
#include<iostream>
using namespacestd;
intCount(unsigned char v)
{
int count = 0;
while(v != 0)
{
count += v & 0x01;
v >>= 1;
}
return count;
}
void main()
{
unsigned char ch = 255;
int count = Count(ch);
cout<<"count ="<<count<<endl;
}
3、 时间复杂度是与1的个数有关的算法
#include<iostream>
using namespacestd;
intCount(unsigned char v)
{
int count = 0;
while(v != 0)
{
v &= (v-1);
count++;
}
return count;
}
void main()
{
unsigned char ch = 255;
int count = Count(ch);
cout<<"count ="<<count<<endl;
}
4、 分支法
#include<iostream>
using namespacestd;
intCount(unsigned char v)
{
int count = 0;
switch (v)
{
case 0x0:
count = 0;
break;
case 0x1:
case 0x2:
case 0x4:
case 0x8:
case 0x10:
case 0x20:
case 0x40:
case 0x80:
count = 1;
break;
case 0x3:
case 0x6:
case 0xc:
case 0x18:
case 0x30:
case 0x60:
case 0xc0:
count = 2;
break;
//...
// [注意] 此处需要把代码补齐
}
return count;
}
void main()
{
unsigned char ch = 255;
int count = Count(ch);
cout<<"count ="<<count<<endl;
}
5、 查表法
#include<iostream>
using namespacestd;
intcountTable[256] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3,3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3,
3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3,4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3,
4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4,
3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3,4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3,
4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4,4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6,
6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3,4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4,
5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4,3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5,6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3,
4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5,5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4,
4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6,7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6,
7, 6, 7, 7, 8
};
intCount(unsigned char v)
{
return countTable[v];
}
void main()
{
unsigned char ch = 255;
int count = Count(ch);
cout<<"count ="<<count<<endl;
}