劍指Offer之二進制中1的個數(shù)(題10)

為睢陽等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及睢陽網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、睢陽網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!

 1 /****************************************                                                                                                 
  2     > File Name:test.c
  3     > Author:xiaoxiaohui
  4     > mail:1924224891@qq.com
  5     > Created Time:2016年05月23日 星期一 21時04分35秒
  6 ****************************************/
  7 
  8 #include<stdio.h>
  9 
 10 int SumOfBit(int num)
 11 {
 12     int count = 0;
 13     int i = 0;
 14 
 15     for(;i <= 32; i++)
 16     {
 17         if( (num & (1 << i)) == 1)    //對應(yīng)的bit位為1
 18         {
 19             count++;
 20         }
 21     }
 22 
 23     return count;
 24 }

 1 /****************************************                                                                                                 
  2     > File Name:test1.c
  3     > Author:xiaoxiaohui
  4     > mail:1924224891@qq.com
  5     > Created Time:2016年05月23日 星期一 21時24分40秒
  6 ****************************************/
  7 
  8 
  9 
 10 
 11 /*這種算法只適應(yīng)于正數(shù)的情況, 當為num為負數(shù)時,在某些平臺下會是死循環(huán)
 12  這種算法如果是正數(shù),則不用算32次循環(huán)了*/
 13 
 14 
 15 #include<stdio.h>
 16 
 17 int NumOfBit(int num)
 18 {
 19     int count = 0;
 20 
 21     while(num != 0)
 22     {
 23         if( (num & 1) == 1)
 24         {
 25             count++;
 26         }
 27 
 28         num >> 1;
 29     }
 30 
 31     return count;
 32 }
~

1 /****************************************                                                                                                 
  2     > File Name:test3.c
  3     > Author:xiaoxiaohui
  4     > mail:1924224891@qq.com
  5     > Created Time:2016年05月23日 星期一 21時30分13秒
  6 ****************************************/
  7 
  8 
  9 
 10 
 11 /*這種算法最佳*/
 12 
 13 #include<stdio.h>
 14 
 15 int NumOfBit(int num)
 16 {
 17     int count = 0;
 18 
 19     while(num != 0)
 20     {
 21         num = num & (num - 1);
 22         count++;
 23     }
 24 
 25     return count;
 26 }

網(wǎng)站名稱:劍指Offer之二進制中1的個數(shù)(題10)
文章來源:http://muchs.cn/article46/jepohg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、網(wǎng)站導航、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、電子商務(wù)、服務(wù)器托管

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司