求從0到n一共有多少個1

1049. Counting Ones (30)

時間限制
100 ms
內存限制
65536 kB
代碼長度限制
16000 B
判題程序
Standard
作者
CHEN, Yue

The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

Input Specification:

Each input file contains one test case which gives the positive N (<=230).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:
12
Sample Output:
5

這個題目是很有趣的,讓我想了很久,在網上找了幾個答案,結果沒一個有像樣的註釋,看不懂,只能自己花了一個小時想出來了。

從0到1000輸出一遍是很有必要的,有助於我們快速找到規律。我們可以很輕鬆的看到,100對應答案21,1000對應答案301,10000對應答案4001.....

也就是說,除了1最高位爲1,每增加10^x次方答案增加的數目是恆定的xi。

遞歸處理第一位,比如第一位數字是a,那麼我們先考慮a00000以前的所有,再遞歸加上a右邊的位數就是答案了。

#include <iostream>
#include <vector>

using namespace std;

int w[]={0,0,1,20,300,4000,50000,600000,7000000,80000000,900000000};
//每10加1,每100加20,每1000加300.......
void init(){//這個是驗算用的
    int sum = 0;
for(int i = 0 ;i<2;i++)
        for(int j = 0;j<10;j++)
        //for(int k=0;k<10;k++)
            for(int l=0;l<10;l++){
            if(i==1)    sum++;
            if(j==1)    sum++;
            //if(k==1)    sum++;
            if(l==1)    sum++;
            cout<<i<<j<<l<<" "<<sum<<endl;
        }
}
int pow(int t){
    int l = 1;
    while(t--)
        l=l*10;
    return l;
}

int f(int n){
    if(n==0)
        return 0;
    if(n<10)
        return 1;
    int wei=0;  //有多少位
    int m = n;
    while(m)
    {
        wei++;
        m/=10;
    }
    int no = pow(wei-1);    //當前位的最小值
    int asdasd=n/no;          //n是不是1開頭的啊
    if(asdasd==1){
        int t = n%no;
        return w[wei]+t+1+f(t);
        //比如 1234就要300 + 234 + 1,這個234+1表示從1000到1234一共有235個千位1,f(t)求百位以後的數
    }
    else
    {   //若是asdasd第一位比1大
        int t = n%no;
        return w[wei]*(asdasd)+no+f(t);
    }

}

int main()
{
   //init();
    int n;
    cin>>n;
    cout<<f(n)<<endl;
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章