統計一個Byte中1的個數,演算法儘可能高效能

來源:互聯網
上載者:User
/*統計一個Byte中1的個數,演算法儘可能高效能*/#include <iostream>using namespace std;//方法1:對2模數得出最後一位,然後除以2實現右移1位,迴圈8次int count1(unsigned char c){int cnt=0;for (int i=0;i!=8;++i){cnt+=c%2;c=c/2;}return cnt;}//方法2:對0x01執行&操作,統計最右邊一位的1,然後右移1位,迴圈8次,o(n)複雜度int count2(unsigned char c){int cnt=0;for (int i=0;i!=8;++i){cnt+=(c&0x01);c>>=1;}return cnt;}//方法3:c=c&(c-1),只統計c中1的個數,迴圈次數是位元組中1的個數,效率比方法2高int count3(unsigned char c){int cnt=0;while (c!=0){c&=(c-1);++cnt;}return cnt;}//方法4:查表法,建立一個含有256個整數的數組,每個整數值代表的是c所在的位置含有1的個數//時間複雜度o(1),空間複雜度o(2^n)int countTable[256]={ 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};int count4(unsigned char c){return countTable[c];}//測試程式int main(){char ch='a';cout<<count1(ch)<<endl;cout<<count2(ch)<<endl;cout<<count3(ch)<<endl;cout<<count4(ch)<<endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.