一、每一位与0x1进行与运算
- int countOne(int num)
- {
- int count = 0;
- while ( num )
- {
- if( num & 1 ){
- ++count;
- }
- num >>= 1;
- }
- return count;
- }
- int countOne2(int num)
- {
- int count = 0;
- while ( num )
- {
- num &= (num - 1) ;
- ++count;
- }
- return count;
- }
- int countOne3(int num)
- {
- // 列举了0到15 的表
- int countTable[16] = {
- 0,1,1,2,
- 1,2,2,3,
- 1,2,2,3,
- 2,3,3,4
- };
- if( num > MAX_SIZE && num < 0 ){
- return -1;
- }
- return countTable[num];
- }