位运算——实现int数中二进制1或0的个数

一、先聊聊存在哪些位运算大笑

1、&(与)          ——   有0则0;无0则1; 
2、|()           ——   有1则1,无1则0; 

3、^(亦或)       ——   相同为0,不同为1; 

4、>>右移(最右边的位被抛弃)

正数,最左边添0;00001010>>3=00000001 

负数,最左边添1;10001010>>3=11110001 

5、<<左移(最左边的位被抛弃)     ——     最右边统一加0; 
(正数)    00001010<<3=01010000 

(负数)    10001010<<3=01010000 

二、具体编程实现,核心代码大笑

2.1 方法一:通过“与”和“左移”操作实现

  1. #include<iostream>
  2. using namespace std;
  3. int NumberOf1(int n)//有符号的n
  4. {
  5. int count=0;
  6. int flag=1;
  7. while (flag)
  8. {
  9. if (n&flag)
  10. {
  11. count++;
  12. }
  13. flag=flag<<1;//左移一位
  14. }
  15. return count;
  16. }
  17. int main()
  18. {
  19. cout<<NumberOf1(9)<<endl;//1001
  20. cout<<NumberOf1(15)<<endl;//1111
  21. return 0;
  22. }

2.2、方法二:只通过“与”操作实现

 
  1. #include<iostream>
  2. using namespace std;
  3. int NemberOf1(int n)
  4. {
  5. int count =0;
  6. while (n)
  7. {
  8. count++;
  9. n=n&(n-1);
  10. }
  11. return count;
  12. }
  13. int main()
  14. {
  15. cout<<NemberOf1(9)<<endl;//1001
  16. cout<<NemberOf1(15)<<endl;//1111
  17. return 0;
  18. }

三、实现int数中二进制0的个数,核心代码大笑

 
  1. int Grial(int x)
  2. {
  3. int count = 0;
  4. while (x + 1)
  5. {
  6. count++;
  7. x |= (x + 1);
  8. }
  9. return count;
  10. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值