判断给定十进制整数的二进制形式中含有几个1
两种判断一个给定整数的二进制形式中含有几个1的简单方法:
主要思想是通过按位与(&)运算和位移运算(<< >>)实现
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依赖于实现。
在第二个方法中,最左边的一位是无法判断的,对于正数,该位是0;对于负数,该位为1,故++count