输入一个整数,求该整数的二进制表达中有多少个1。

例如输入10,由于其二进制表示为1010,有两个1,因此输出2。

分析:

这是一道很基本的考查位运算的面试题。

包括微软在内的很多公司都曾采用过这道题。

ANSWER

Traditional question. Use the equation xxxxxx10000 & (xxxxxx10000-1) = xxxxxx00000

Note: for negative numbers, this also hold, even with 100000000 where the “-1” leading to an underflow.

 int countOf1(int n) {
   int c=0;
   while (n!=0) {
     n=n & (n-1);
     c++;
   }
   return c;
 }
 another solution is to lookup table. O(k), k is sizeof(int);
 int countOf1(int n) {
     int c = 0;
     if (n<0)
 { 
   c++;
   n = n & (1<<(sizeof(int)*8-1)); 
  }
     while (n!=0)
 {
       c+=tab[n&0xff];
       n >>= 8;
     }
     return c;
}