1. 程式人生 > >求一個整數的二進位制中1的個數

求一個整數的二進位制中1的個數

題目:輸入一個整數,求該整數的二進位制表達中有多少個1。例如輸入10,由於其二進位制表示為1010,有兩個1,因此輸出2。

分析:這是一道很基本的考查位運算的面試題。包括微軟在內的很多公司都曾採用過這道題。

一個很基本的想法是,我們先判斷整數的最右邊一位是不是1。接著把整數右移一位,原來處於右邊第二位的數字現在被移到第一位了,再判斷是不是1。這樣每次移動一位,直到這個整數變成0為止。現在的問題變成怎樣判斷一個整數的最右邊一位是不是1了。很簡單,如果它和整數1作與運算。由於1除了最右邊一位以外,其他所有位都為0。因此如果與運算的結果為1,表示整數的最右邊一位是1,否則是0。

得到的程式碼如下:

///////////////////////////////////////////////////////////////////////
// Get how many 1s in an integer's binary expression

///////////////////////////////////////////////////////////////////////
int NumberOf1_Solution1(int i)
{
      int count = 0;
      while(i)
      {
            if(i & 1)
                  count ++;

            i = i >> 1;
      }

      return count;
}

可能有讀者會問,整數右移一位在數學上是和除以2是等價的。那可不可以把上面的程式碼中的右移運算子換成除以2呢?答案是最好不要換成除法。因為除法的效率比移位運算要低的多,在實際程式設計中如果可以應儘可能地用移位運算子代替乘除法。

這個思路當輸入

i是正數時沒有問題,但當輸入的i是一個負數時,不但不能得到正確的1的個數,還將導致死迴圈。以負數0x80000000為例,右移一位的時候,並不是簡單地把最高位的1移到第二位變成0x40000000,而是0xC0000000。這是因為移位前是個負數,仍然要保證移位後是個負數,因此移位後的最高位會設為1。如果一直做右移運算,最終這個數字就會變成0xFFFFFFFF而陷入死迴圈。

為了避免死迴圈,我們可以不右移輸入的數字i。首先i1做與運算,判斷i的最低位是不是為1。接著把1左移一位得到2,再和i做與運算,就能判斷i的次高位是不是1……這樣反覆左移,每次都能判斷i的其中一位是不是1。基於此,我們得到如下程式碼:

///////////////////////////////////////////////////////////////////////
// Get how many 1s in an integer's binary expression

///////////////////////////////////////////////////////////////////////
int NumberOf1_Solution2(int i)
{
      int count = 0;
      unsigned int flag = 1;
      while(flag)
      {
            if(i & flag)
                  count ++;

            flag = flag << 1;
      }

      return count;
}

另外一種思路是如果一個整數不為0,那麼這個整數至少有一位是1。如果我們把這個整數減去1,那麼原來處在整數最右邊的1就會變成0,原來在1後面的所有的0都會變成1。其餘的所有位將不受到影響。舉個例子:一個二進位制數1100,從右邊數起的第三位是處於最右邊的一個1。減去1後,第三位變成0,它後面的兩位0變成1,而前面的1保持不變,因此得到結果是1011

我們發現減1的結果是把從最右邊一個1開始的所有位都取反了。這個時候如果我們再把原來的整數和減去1之後的結果做與運算,從原來整數最右邊一個1那一位開始所有位都會變成0。如1100&1011=1000。也就是說,把一個整數減去1,再和原整數做與運算,會把該整數最右邊一個1變成0。那麼一個整數的二進位制有多少個1,就可以進行多少次這樣的操作。

這種思路對應的程式碼如下:

///////////////////////////////////////////////////////////////////////
// Get how many 1s in an integer's binary expression
///////////////////////////////////////////////////////////////////////
int NumberOf1_Solution3(int i)
{
      int count = 0;
      while (i)
      {
            ++ count;
            i = (i - 1) & i;
      }

      return count;
}

擴充套件:如何用一個語句判斷一個整數是不是二的整數次冪?

PS:n&(n-1)==0;//二進位制數只有一位位1,則該數是2的整數次冪.

簡單查表,相對來說效率也不錯。

int countBits(int value){ 
int count=0;
int bits4[]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
while(value!=0){
count+=bits4[value&0xf];
value>>=4;
}
return count;
}

======================================================

這是一道《程式設計之美-微軟技術面試心得》中的題目,問題描述如下:

對於一個位元組(8bit)的變數,求其二進位制表示中“1”的個數,要求演算法的執行效率儘可能地高。

《程式設計之美》中給出了五種解法,但是實際上從 Wikipedia 上我們可以找到更優的演算法

這道題的本質相當於求二進位制數的 Hamming 權重,或者說是該二進位制數與 0 的 Hamming 距離,這兩個概念在資訊理論和編碼理論中是相當有名的。在二進位制的情況下,它們也經常被叫做 population count 或者 popcount 問題,比如 gcc 中就提供了一個內建函式:

int __builtin_popcount (unsigned int x)

輸出整型數二進位制中 1 的個數。但是 GCC 的 __builtin_popcount 的實現主要是基於查表法做的,跟程式設計之美中解法 5 是一樣的。Wikipedia 上的解法是基於分治法來做的,構造非常巧妙,通過有限次簡單地算術運算就能求得結果,特別適合那些受儲存空間限制的演算法中使用:

/* ===========================================================================
* Problem: 
*   The fastest way to count how many 1s in a 32-bits integer.
*
* Algorithm:
*   The problem equals to calculate the Hamming weight of a 32-bits integer,
*   or the Hamming distance between a 32-bits integer and 0. In binary cases,
*   it is also called the population count, or popcount.[1]
*
*   The best solution known are based on adding counts in a tree pattern
*   (divide and conquer). Due to space limit, here is an example for a
*   8-bits binary number A=01101100:[1]
* | Expression            | Binary   | Decimal | Comment                    |
* | A                     | 01101100 |         | the original number        |
* | B = A & 01010101      | 01000100 | 1,0,1,0 | every other bit from A     |
* | C = (A>>1) & 01010101 | 00010100 | 0,1,1,0 | remaining bits from A      |
* | D = B + C             | 01011000 | 1,1,2,0 | # of 1s in each 2-bit of A | 
* | E = D & 00110011      | 00010000 | 1,0     | every other count from D   |
* | F = (D>>2) & 00110011 | 00010010 | 1,2     | remaining counts from D    |
* | G = E + F             | 00100010 | 2,2     | # of 1s in each 4-bit of A |
* | H = G & 00001111      | 00000010 | 2       | every other count from G   |
* | I = (G>>4) & 00001111 | 00000010 | 2       | remaining counts from G    |
* | J = H + I             | 00000100 | 4       | No. of 1s in A             |
* Hence A have 4 1s.
*
* [1] http://en.wikipedia.org/wiki/Hamming_weight
*
* 這個演算法的設計思想用的是二分法,兩兩一組相加,之後四個四個一組相加,接著八個八個,最後就得到各位之和了。

* 設原整數值為x,
* 第一步:把x的32個bit分成16組(第32bit和第31bit一組,第30bit和第29bit一組……以此類推),然後將每一組
兩bit上的值(因為是二進位制數,所以要麼是0要麼是1)相加並把結果還放在這兩bit的位置上,這樣,得到結果整數x1,x1的二進位制(32bit)可以分為16組,每一組的數值就是原來整數x在那兩bit上1的個數。
* 第二步:把第一步得到的結果x1的32bit,分成8組(第32、31、30、29bit一組,第28、27、26、25bit一組……
以此類推),然後每一組的四bit上的值相加並把結果還放在這四bit的位置上,這樣,又得到結果整數x2,x2的二進位制可以分為8組,每一組的數值就是原來整數x在那四bit上的1的個數。
* ……
* 這樣一直分組計算下去,最終,把兩個16bit上1的個數相加,得到原來整數x的32bit上1的個數。

===========================================================================
*/
#include <stdio.h>

typedef unsigned int UINT32;
const UINT32 m1  = 0x55555555;  // 01010101010101010101010101010101
const UINT32 m2  = 0x33333333;  // 00110011001100110011001100110011
const UINT32 m4  = 0x0f0f0f0f;  // 00001111000011110000111100001111
const UINT32 m8  = 0x00ff00ff;  // 00000000111111110000000011111111
const UINT32 m16 = 0x0000ffff;  // 00000000000000001111111111111111
const UINT32 h01 = 0x01010101;  // the sum of 256 to the power of 0, 1, 2, 3

/* This is a naive implementation, shown for comparison, and to help in 
* understanding the better functions. It uses 20 arithmetic operations
* (shift, add, and). */
int popcount_1(UINT32 x)
{
  x = (x & m1) + ((x >> 1) & m1);
  x = (x & m2) + ((x >> 2) & m2);
  x = (x & m4) + ((x >> 4) & m4);
  x = (x & m8) + ((x >> 8) & m8);
  x = (x & m16) + ((x >> 16) & m16);
  return x;
}

/* This uses fewer arithmetic operations than any other known implementation
* on machines with slow multiplication. It uses 15 arithmetic operations. */
int popcount_2(UINT32 x)
{
  x -= (x >> 1) & m1;             //put count of each 2 bits into those 2 bits
  x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits 
  x = (x + (x >> 4)) & m4;        //put count of each 8 bits into those 8 bits 
  x += x >> 8;           //put count of each 16 bits into their lowest 8 bits
  x += x >> 16;          //put count of each 32 bits into their lowest 8 bits
  return x & 0x1f;
}

/* This uses fewer arithmetic operations than any other known implementation
* on machines with fast multiplication. It uses 12 arithmetic operations, 
* one of which is a multiply. */
int popcount_3(UINT32 x)
{
  x -= (x >> 1) & m1;             //put count of each 2 bits into those 2 bits
  x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits 
  x = (x + (x >> 4)) & m4;        //put count of each 8 bits into those 8 bits 
  return (x * h01) >> 24;  // left 8 bits of x + (x<<8) + (x<<16) + (x<<24)
}

int main()
{
  int i = 0x1ff12ee2
  printf("i = %d = 0x%x/n", i, i);
  printf("popcount_1(%d) = %d/n", i, popcount_1(i));
  printf("popcount_2(%d) = %d/n", i, popcount_2(i));
  printf("popcount_3(%d) = %d/n", i, popcount_3(i));
  /* If compiled with other compiler than gcc, comment the line bellow. */
  printf("GCC's  __builtin_popcount(%d) = %d/n", i,  __builtin_popcount(i));
  return 0;
}

===========================================================

HAKMEM演算法:

int Count(unsigned x)
{
    unsigned n;   

    n = (x >> 1) & 033333333333;    
    x = x - n;   
    n = (n >> 1) & 033333333333;   
    x = x - n;    
    x = (x + (x >> 3)) & 030707070707;   
    x = modu(x, 63);  
    return x;   

說明:首先是將二進位制各位三個一組,求出每組中1的個數,然後相鄰兩組歸併,得到六個一組的1的個數,最後很巧妙的用除63取餘得到了結果。
因為2^6 = 64,也就是說 x_0 + x_1 * 64 + x_2 * 64 * 64 = x_0 + x_1 + x_2 (mod 63),這裡的等號表示同餘。
這個程式只需要十條左右指令,而且不訪存,速度很快。