小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

【轉(zhuǎn)】輸入一個整數(shù),求該整數(shù)的二進制中有多少位1

 yyy2k3 2013-08-16

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

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

一個很基本的想法是,我們先判斷整數(shù)的最右邊一位是不是1。接著把整數(shù)右移一位,原來處于右邊第二位的數(shù)字現(xiàn)在被移到第一位了,再判斷是不是1。這樣每次移動一位,直到這個整數(shù)變成0為止?,F(xiàn)在的問題變成怎樣判斷一個整數(shù)的最右邊一位是不是1了。很簡單,如果它和整數(shù)1作與運算。由于1除了最右邊一位以外,其他所有位都為0。因此如果與運算的結(jié)果為1,表示整數(shù)的最右邊一位是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;
}

可能有讀者會問,整數(shù)右移一位在數(shù)學(xué)上是和除以2是等價的。那可不可以把上面的代碼中的右移運算符換成除以2呢?答案是最好不要換成除法。因為除法的效率比移位運算要低的多,在實際編程中如果可以應(yīng)盡可能地用移位運算符代替乘除法。

這個思路當(dāng)輸入i是正數(shù)時沒有問題,但當(dāng)輸入的i是一個負數(shù)時,不但不能得到正確的1的個數(shù),還將導(dǎo)致死循環(huán)。以負數(shù)0x80000000為例,右移一位的時候,并不是簡單地把最高位的1移到第二位變成0x40000000,而是0xC0000000。這是因為移位前是個負數(shù),仍然要保證移位后是個負數(shù),因此移位后的最高位會設(shè)為1。如果一直做右移運算,最終這個數(shù)字就會變成0xFFFFFFFF而陷入死循環(huán)。

為了避免死循環(huán),我們可以不右移輸入的數(shù)字i。首先i1做與運算,判斷i的最低位是不是為1。接著把1左移一位得到2,再和i做與運算,就能判斷i的次高位是不是1……這樣反復(fù)左移,每次都能判斷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;
}

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

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

這種思路對應(yīng)的代碼如下:

///////////////////////////////////////////////////////////////////////
// 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;
}

擴展:如何用一個語句判斷一個整數(shù)是不是二的整數(shù)次冪?

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

 

 

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

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;
}

 

 

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

 

這是一道《編程之美-微軟技術(shù)面試心得》中的題目,問題描述如下:

對于一個字節(jié)(8bit)的變量,求其二進制表示中“1”的個數(shù),要求算法的執(zhí)行效率盡可能地高。

《編程之美》中給出了五種解法,但是實際上從 Wikipedia 上我們可以找到更優(yōu)的算法。

這道題的本質(zhì)相當(dāng)于求二進制數(shù)的 Hamming 權(quán)重,或者說是該二進制數(shù)與 0 的 Hamming 距離,這兩個概念在信息論和編碼理論中是相當(dāng)有名的。在二進制的情況下,它們也經(jīng)常被叫做 population count 或者 popcount 問題,比如 gcc 中就提供了一個內(nèi)建函數(shù):

int __builtin_popcount (unsigned int x)

輸出整型數(shù)二進制中 1 的個數(shù)。但是 GCC 的 __builtin_popcount 的實現(xiàn)主要是基于查表法做的,跟編程之美中解法 5 是一樣的。

注:我查到的算法是這樣的,并非查表,而是Wikipedia 上的方法
 
_LIBCPP_ALWAYS_INLINE int __builtin_popcount(unsigned int x) {
   static const unsigned int m1 = 0x55555555; //binary: 0101...
   static const unsigned int m2 = 0x33333333; //binary: 00110011..
   static const unsigned int m4 = 0x0f0f0f0f; //binary:  4 zeros,  4 ones ...
   static const unsigned int h01= 0x01010101; //the sum of 256 to the power of 0,1,2,3...
   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;  //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24)
}
 
Wikipedia 上的解法是基于分治法來做的,構(gòu)造非常巧妙,通過有限次簡單地算術(shù)運算就能求得結(jié)果,特別適合那些受存儲空間限制的算法中使用:

/* ===========================================================================
* 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./wiki/Hamming_weight
*
* 這個算法的設(shè)計思想用的是二分法,兩兩一組相加,之后四個四個一組相加,接著八個八個,最后就得到各位之和了。

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

===========================================================================
*/
#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的個數(shù),然后相鄰兩組歸并,得到六個一組的1的個數(shù),最后很巧妙的用除63取余得到了結(jié)果。
因為2^6 = 64,也就是說 x_0 + x_1 * 64 + x_2 * 64 * 64 = x_0 + x_1 + x_2 (mod 63),這里的等號表示同余。
這個程序只需要十條左右指令,而且不訪存,速度很快。

本文來自CSDN博客:http://blog.csdn.net/chinazjf/archive/2008/04/15/2294840.aspx

 
 
 

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多