【c筆記】一個很好的編程題

來源:互聯網
上載者:User

                               一個很好的編程題

    今天在某qq群見到有人問下面這個題目,當時沒太多思路,跟他討論了下,突然想出了做法。

    於是,馬上編程實踐,沒想到,不久就把它實現了。好有成就感。。。

    

  1+11+111+1111+..........+11.....11(最後為2009個1)  求和中共有幾個1
     (以上為10進位數)

  我的答案:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #define size 2009
 4 
 5 void main()
 6 {
 7     int result[size] = {0};//存結果中每位所得到的進位值
 8     int count = 0;//結果中1的個數
 9     int numOfbit=size;//存現在判斷的位不加進位的值
10 
11     for(int i=0;i<size;i++)
12     {//迴圈判斷結果中每位是否為1,並處理進位
13         if(1 == (numOfbit + result[i])%10)
14         {//判斷此位是否為1
15             count++;
16         }
17         
18         if(numOfbit>9)
19         {//處理進位
20             int val = numOfbit%10;
21             int bit = i+1;//要進位的對應位下標
22             do
23             {
24                 result[bit] += val%10;
25                 val = val%10;
26                 bit++;
27             }
28             while(val>=10);
29         }
30         numOfbit--;
31     }
32 
33     printf("結果中1的個數為%d\n",count);
34 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.