快起来,这真的是最后一篇啦!
计算非零位的个数 / counting the number of bits set
例1:测试单个的最低位,计数,然后移位。
//example1
int countbit1(uint n)
{
int bits = 0;
while (n != 0) {
if(n & 1) bits++;
n >>= 1;
}
return bits;
}
例2:先除4,然后计算被4处的每个部分。循环拆解经常会给程序优化带来新的机会。
//example - 2
int countbit2(uint n)
{
int bits = 0;
while (n != 0) {
if (n & 1) bits++;
if (n & 2) bits++;
if (n & 4) bits++;
if (n & 8) bits++;
n >>= 4;
}
return bits;
}
尽早地退出循环 / Early loop breaking
通常没有必要遍历整个循环。举例来说,在数组中搜索一个特定的值,我们可以在找到我们需要值之后立刻退出循环。下面的例子在10000个数字中搜索-99。
found = FALSE;
for(i=0;i<10000;i