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

按个,十,百,千....一位一位算一的数目累加即可

#include <bits/stdc++.h>
#include <iomanip>
typedef long long LL;
using namespace std;
#define SIZE 105
LL n,res = 0;
int main(){
    // freopen("test.in","r",stdin);
    cin >> n;
    LL now = 1;
    while (true){
       // cout << res << endl;
       LL temp = res;
       if (n % (now*10) >= (2*now)){
         res += (n / (now * 10) + 1) * now;
       }
       else {
         res += (n / (now * 10)) * now + max(n % (now * 10) - now + 1,(LL)0);
       }
       if (temp >= res) {
        res = temp; break;
       }
       now = now * 10;
    }
    cout << res;
    return 0;
}
View Code

 

posted on 2018-02-16 21:49  Crutain  阅读(166)  评论(0编辑  收藏  举报