給定一個十進位正整數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?
- #include<iostream>
- using namespace std;
-
- unsigned long Sumls(unsigned long n);
-
- int main()
- {
-
- cout<< Sumls(1);
- return 0;
- }
-
- unsigned long Sumls(unsigned long n)
- {
- unsigned long iCount=0;
- unsigned long iFactor=1;
- unsigned long iLowerNum=0;
- unsigned long iCurrNum=0;
- unsigned long iHigherNum=0;
-
- while(n/iFactor!=0)
- {
- iLowerNum=n-(n/iFactor)*iFactor;
- iCurrNum=(n/iFactor)%10;
- iHigherNum=n/(iFactor*10);
-
- switch(iCurrNum)
- {
- case 0:
- iCount+=iHigherNum*iFactor;
- break;
- case 1:
- iCount+=iHigherNum*iFactor+iLowerNum+1;
- break;
- default:
- iCount+=(iHigherNum+1)*iFactor;
- break;
-
- }
- iFactor+=10;
- }
- return iCount;
-
-
-
- }