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 (≤2
30
).
Output Specification:
For each test case, print the number of 1’s in one line.
Sample Input:
12
Sample Output:
5
暴力也有20多
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main(){
int n, sum = 0, radix = 1, left, curr, right;
scanf("%d",&n);
while(n/radix){
left = n/(radix * 10);
curr = n/radix%10;
right = n%radix;
if(curr == 0) sum += left*radix;
else if(curr == 1) sum += left*radix + right+1;
else if(curr >= 2) sum += (left+1)*radix;
radix *= 10;
}
printf("%d",sum);
return 0;
}