比如,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; }
上述代碼中尚未考慮負數的情況,其中棧僅僅是用來顯示該數的二進制表示。