統計一個數二進制表示中1的個數

比如,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;
}

運行結果如下:







上述代碼中尚未考慮負數的情況,其中棧僅僅是用來顯示該數的二進制表示。
發佈了45 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章