編程之美 1的數目

來源:互聯網
上載者:User

給定一個十進位正整數N,寫下從1開始,到N的所有整數,然後數一下其中出現的所有”1“的個數。

       解法一:窮舉法,遍曆1到N的每一個數,計算其出現1的整數的個數;雖然笨,但是想不出其他方法就這樣了;

 

      解法二:分類討論,分別討論個位,十位和百位...上1能出現的次數。

      假設這個數為abcd,則:

     d 為1時,出現1的資料的個數有abc個;

     c為1時,出現1的資料的個數有abd個;

     b為1時,出現1的資料的個數有acd個;

     a為1時,出現1的資料的個數有bcd個;

      當然具體還要看當前位置是0或是1,稍微調整。

      上代碼:

[cpp]
view plaincopyprint?
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. unsigned long Sumls(unsigned long n);  
  5.   
  6. int main()  
  7. {  
  8.   
  9.  cout<< Sumls(1);  
  10. return 0;  
  11. }  
  12.   
  13. unsigned long Sumls(unsigned long n)  
  14. {  
  15.    unsigned long iCount=0;  
  16.    unsigned long iFactor=1;  
  17.    unsigned long iLowerNum=0;  
  18.    unsigned long iCurrNum=0;  
  19.    unsigned long iHigherNum=0;  
  20.   
  21.    while(n/iFactor!=0)  
  22.    {  
  23.       iLowerNum=n-(n/iFactor)*iFactor;  
  24.       iCurrNum=(n/iFactor)%10;  
  25.       iHigherNum=n/(iFactor*10);  
  26.   
  27.       switch(iCurrNum)  
  28.       {  
  29.       case 0:  
  30.           iCount+=iHigherNum*iFactor;  
  31.           break;  
  32.       case 1:  
  33.           iCount+=iHigherNum*iFactor+iLowerNum+1;  
  34.           break;  
  35.       default:  
  36.           iCount+=(iHigherNum+1)*iFactor;  
  37.           break;  
  38.         
  39.       }  
  40.       iFactor+=10;  
  41.    }  
  42.    return iCount;  
  43.   
  44.   
  45.   

聯繫我們

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