统计一个数二进制表示中1的个数

来源:互联网 发布:80端口开启 编辑:程序博客网 时间:2024/05/16 05:48

比如,8的二进制表示为1000,则1的个数为1

实现原理:一个数n,n&n-1的结果等价于将n的二进制表示中最右的一个1变成0.

例如:9(1001),9&8 = 1001 & 1000 = 1000,1001最右边的1变成了0

实现如下:

#include<iostream>#include<stack>using namespace std;class Binary{public:         Binary(int n):n(n){}        void binaryDisplay();        void countOne();private:        int n;};void Binary::binaryDisplay(){        if(n<0){                cout<<"not considered"<<endl;                   return ;        }        stack<int> bit;        int quotient=0,dividedevenly=n;        while((quotient = dividedevenly / 2) != 0){                bit.push(dividedevenly % 2);                dividedevenly = quotient;        }        bit.push(dividedevenly % 2);        while(!bit.empty()){                cout<<bit.top();                bit.pop();        }        cout<<endl;}void Binary::countOne(){        int m=n;        if(m<0){                cout<<"not considered"<<endl;                   return ;        }        int count=0;        while(m){                m &= m-1;                count++;        }        cout<<"number of 1: "<<count<<endl;}int main(){        Binary b(0);        b.binaryDisplay();        b.countOne();        cout<<endl;        Binary b1(9);        b1.binaryDisplay();        b1.countOne();        cout<<endl;        Binary b2(-5);        b2.binaryDisplay();        b2.countOne();        return 0;}

运行结果如下:







上述代码中尚未考虑负数的情况,其中栈仅仅是用来显示该数的二进制表示。