兩種判斷一個給定整數的二進制形式中含有幾個1的簡單方法:spa
主要思想是經過按位與(&)運算和位移運算(<< >>)實現code
1 unsigned int_number( int n) 2 { 3 if (n < 0) 4 return; 5 unsigned count = 0; 6 while (n != 0) 7 { 8 if ((n & 1) != 0) 9 ++count; 10 n >>= 1; 11 } 12 return count; 13 } 14 15 unsigned int_number2(int n) 16 { 17 unsigned count = 0; 18 int factor = 1; 19 while (factor > 0) 20 { 21 if ( (n & factor) != 0 ) 22 ++count; 23 factor <<= 1; 24 } 25 if (n < 0) 26 ++count; 27 return count; 28 } 29 30 int main() 31 { 32 cout << "Please enter an integer: "; 33 int num; 34 cin >> num; 35 cout << num << " contains " << int_number(num) << " 1." << endl; 36 cout << num << " contains " << int_number2(num) << " 1." << endl; 37 38 return 0; 39 }
一個負整數進行右移操做時,左邊補0仍是補1依賴於實現。blog
在第二個方法中,最左邊的一位是沒法判斷的,對於正數,該位是0;對於負數,該位爲1,故++countci