剑指offer 面试题15 二进制中1的个数

题目描述:
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

可能首先会想到,每次把这个数进行除以2,或者进行右移操作,但是考虑到负数的情况,并不适用

可以借助一个flag, 保持n不动,而每次左移flag(这个flag是unsigned类型)

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<cmath>
#include<algorithm>
using namespace std;

class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         unsigned int flag=1;
         while(flag!=0) {
             if((n&flag)!=0) {
                 count++;
             }
             flag=flag<<1;
         }
         return count;
     }
};

另有一种更简洁,更快速的办法,n&(n-1)每次将n最右边的1变为0,复杂度与n中1的个数有关:

class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         while(n) {
             n=n&(n-1);
             count++;
         }
         return count;
     }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值