求一个数的二进制的位数

#include <stdarg.h>
#include <stdio.h>

int ripple(int n, ...)
{
   int i, j, k;
   va_list p;

   k = 0;
   j = 1;
   va_start(p, n);

   for (; j < n; ++j)
   {
      i = va_arg(p, int);
      for (; i; i &= i - 1)
         ++k;
   }
   va_end(p);
   return k;
}

int main(void)
{
   printf("%d\n", ripple(3, 5, 7));
   return 0;
}

答案为:
5

The va_arg macro produces the arguments passed as the “...” part of a variadic function.  In ripple it will be called twice, setting i first to 5, then to 7.

The expression i &= i - 1 resets the right-most 1 bit in i.  For example, if i is 6 (binary 110), i & i - 1 is 4 (binary 100).  The inner for loop executes until i is 0, so k is increased by the number of 1 bits in i.

There are two 1 bits in 5 (binary 101) and three in 7 (binary 111), so ripple returns 5.


这道题也是两个知识点,一个是可变参数函数定义以及如何实现,va_arg会把5,7依次取出来。另一个知识点是i &= i-1,实际上是计算了i二进制形式中1的个数,每次计算都会消减掉最低有效位上的1。比如7二进制表示为111。i &= i –1的计算结果依次为110,100, 000 (也就是0)。在hacker's Delights这本书里介绍了很多类似技巧。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值