面試訓練求數字裡面1的個數

來源:互聯網
上載者:User

我的思路1 的話 就是用空間換時間吧。輸入為n然後分配一個n為幾位元 分配一個n*位元的字串,然後sprintf(str,“%d”,num)往字串輸入,最後

從頭到為遍曆字串就能求出1的個數。代碼如下:

#include "stdio.h"#include "stdlib.h"int main(){int n;int num;int digit=0,index=0;char *str;int total;scanf("%d",&n);num=n;while(n){n/=10;++digit;}        str = calloc(digit*num+1,1);memset(str,0,digit*num);str[0]='\0';for(index=1;index<=num;index++){sprintf(str+strlen(str),"%d",index);}index=0;total=0;while(str[index]!='\0'){if(str[index]=='1')total++;index++;}printf("%d\n",total);free(str);return 0;}

這道題目的解法

1 面試寶典有 不過過於複雜,沒時間分析,而且變數名給的相當難以明白

2 海濤的書上也有相關的解法,還要用什麼遞迴之類的,感覺好複雜啊。

直到遇見了一位部落格園的網友文章,我才是豁然開朗,如釋重負啊。

思路怎樣的呢。

假如輸入 的數 為21356

如何計算呢? 當然從低位開始咯

低位為6 :  >1  那麼 1的數目  就為高於它的數字 加1,然後乘以該位的加權。

                        (2135+1)*1

十位為5 :(213+1)*10

百位為3: (21+1)*100

千位為1:當為1的時候,需要考慮高位和低位,顯然如果有高位不為0的話 X1999--- X1000這種情況還是有的吧,同時還要考慮低位就是 1000-1xxx這裡面的數字當然

                   就為 xxx+1

萬位為2:(0+1)*10000

還有一種情況沒有說明 即當該位為0時 如何處理。

此時 只需處理高位就行了 比如   10xx 顯然 為(1+0)*100。為什麼不考慮低位呢,因為把高位去掉,那麼百位就為0,不需要考慮後面的了。

好了上代碼吧

#include "stdio.h"#include "stdlib.h"int main(){  int n;  int factor=1;  int lower=0;  int current=0;  int higher=0;  int sum =0;  scanf("%d",&n);  while(n/factor!=0)  {lower=n-(n/factor)*factor;current = (n/factor)%10;higher =(n/factor)/10;switch(current){case 0: sum+=higher*factor;break;case 1: sum+=(higher*factor+lower+1);break;default:sum+=((higher+1)*factor);break;}factor*=10;  }  printf("%d",sum); 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.