题目:
Write the function int bitCount(short input) that takes a short as input and
returns an int. The function returns the number of bits set in the input
variable. For instance:
bitCount(7) --> 3
bitCount(2543) --> 9
bitCount(11111) --> 9
解答:
之前已经给出了两种算法,优化版中的算法已经算是最高效的了。在这里再给出一个算法,可能效率没有优化版中的算法高,不过能给大家一些提示。
int func(x)
{
int countx = 0;
while (x)
{
countx ++;
x = x&(x-1);
}
return countx;
}
从这里头,我们需要注意的一个关键元素就是:如果 x 为2的 n 次幂( n 为整数),那么可以得到一个公式:
~x == (x-1)
因此: x & (x-1) == x & (~x) == 0
从上面的while循环中可以看出,每次执行的操作都是计数,并把做后一位清零的过程,依次就能计算出整数中1的位数了。
/*******************************************************/
在这里,也可以看看另外一道题:
用一条语句实现x是否为2的若干次幂的判断
很容易,我们就可以得到答案:
#define ISXXX(x) (x&(x-1) ? FALSE : TRUE)