溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

劍指Offer之二進(jìn)制中1的個(gè)數(shù)(題10)

發(fā)布時(shí)間:2020-06-13 13:30:13 來源:網(wǎng)絡(luò) 閱讀:254 作者:ye小灰灰 欄目:編程語言





 1 /****************************************                                                                                                 
  2     > File Name:test.c
  3     > Author:xiaoxiaohui
  4     > mail:1924224891@qq.com
  5     > Created Time:2016年05月23日 星期一 21時(shí)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)    //對(duì)應(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時(shí)24分40秒
  6 ****************************************/
  7 
  8 
  9 
 10 
 11 /*這種算法只適應(yīng)于正數(shù)的情況, 當(dāng)為num為負(fù)數(shù)時(shí),在某些平臺(tái)下會(huì)是死循環(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時(shí)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 }


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI