2014年10月25日 星期六

求一個整數的二進制中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。首先i和1做與運算,判斷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;
}

以上內容來源於http://blog.solrex.cn/articles/population-count-problem.html


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



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),這裡的等號表示同餘。
這個程序只需要十條左右指令,而且不訪存,速度很快。

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

寫一個前置處理器的巨集,可交換兩個整數(如果你是屬於駭客級,就不要透過宣告在巨集外部的暫時變數)

#define swap(x,y) {x=x^y;y=x^y;x=x^y;}  //a,b數值交換

x=x^y
//表示將 x xor y 之後的值存至x  又因為 xor有可逆性所以可以看做 x在這等式之後成為x與y的綜合體
y=x^y
//因為可逆性,所以將這個綜合體x與y結合,會還原成原本的x,此時將結果存為y
x=x^y
//此時的y內存的結果已經為一開始的x了,所以x^y的結果為  x與y的綜合體在與x做運算,得到一開始的y,存為x。
swap結束

C++風格與藝術 CH10 前置處理器

#define name Substitue_text
name 為任意變數
Substitue_text 可以為任意內容,包含空白 括號等皆可

e.g.
#define FOR_ALL for (i=0;i<array_size;++i)

定義常數上const 較 define為佳
1. const 為C++語法 define不是
2. C++會立即檢查const的語法是否有錯,但define會在巨集呼叫才檢測
3. const 適用c++的有效範圍規定,但define一律是全域宣告

define在條件編譯和其他特定應用上較有優勢




2014年10月16日 星期四

20141017 C++閱讀紀錄 字元字串(寬字元寬字串)

字元使用 char
寬字元使用 wchar_t
e.g.
char simple; //普通的字元
wchar_t wide;  // 寬字元
simple = ''X';
wide = L'Ω';

//特殊狀況
char simple = 'ab';
std::cout << simple ;
則會產生overflow 但程式能可正常執行,且印出結果為 b;

使用字串方法
#include <string>
std::string name; //宣告字串 name
寬字串比照上面

C的字串與C轉C++ 請直接參考C++風格與藝術 第五章 說明

C++字串與C字串差異
C++字串較易使用,並已設計能防止眾多問題發生。
e.g. 字串長度限制 c++可自動沒有長度限制。
C的字串處理速度較C++快,因為string類別需要額外成本
但是幾乎所有程式在這個速度上的差距是可以忽略不記的。

int num = 0123;
std::cout << num ;
輸出為 83
因為會被誤以為是8進位