CSAPP:Lab的Datalab中bitCount的思路

 不得不说CSAPP:Lab对于我这样的小白来说的难度还是挺高的,bitCount这题是通过百度才解出来的...

原题:

/*
 * bitCount - returns count of number of 1's in word
 *   Examples: bitCount(5) = 2, bitCount(7) = 3
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 40
 *   Rating: 4
 */
int bitCount(int x) {
  // Write code here...
}

由于操作符总数限制为40个,因此采用二分法。

首先是基本思路:


而要分组和相加就要通过掩码和移位来实现了。

最后代码如下:

int bitCount(int x) {
    int count;
    
    int tmpMask1 = (0x55)|(0x55<<8);
    int mask1 = (tmpMask1)|(tmpMask1<<16);  //得到掩码: 01010101……01010101
    
    int tmpMask2 = (0x33)|(0x33<<8);
    int mask2 = (tmpMask2)|(tmpMask2<<16);  //得到掩码: 00110011……00110011
    
    int tmpMask3 = (0x0f)|(0x0f<<8);
    int mask3 = (tmpMask3)|(tmpMask3<<16);  //得到掩码: 00001111……00001111
    
    int mask4 = (0xff)|(0xff<<16);          //得到掩码: 0000 0000 1111 1111 0000 0000 1111 1111
    
    int mask5 = (0xff)|(0xff<<8);           //得到掩码: 0000 0000 0000 0000 1111 1111 1111 1111
    
    count = (x&mask1)+((x>>1)&mask1);       //分别计算每组2位中,低位的1的个数;再移位求每组2位中,高位的1的个数;求和
    count = (count&mask2)+((count>>2)&mask2);   //两两相加
    count = (count + (count >> 4)) & mask3;     //同理,两两相加
    count = (count + (count >> 8)) & mask4;     //同理,两两相加
    count = (count + (count >> 16)) & mask5;    //同理,两两相加
    return count;
}






  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值