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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 int main(){ 5 long long N, a = 10, ans = 0, left, mid, right; 6 scanf("%lld", &N); 7 while(N / (a / 10) != 0){ 8 left = N / a; 9 mid = N % a / (a / 10); 10 right = N % (a / 10); 11 if(mid == 0) 12 ans += left * (a / 10); 13 else if(mid == 1) 14 ans += left * (a / 10) + right + 1; 15 else if(mid > 1) 16 ans += (left + 1) * (a / 10); 17 a *= 10; 18 } 19 printf("%d", ans); 20 cin >> N; 21 return 0; 22 }
总结:
1、本题应寻找规律完成。对于数字abcde来说,讨论第c位为1的有多少个数字,分为左边:ab,中间c, 右边de。当c = 1时,ab可以取0到ab的任意数字,当取0到ab - 1时,de位任意取。当ab取ab时,de位只能从0 到 de, 故共有ab * 1000 + de + 1个。 当c = 0时,为了让c能 = 1, ab位只能取0 到 ab - 1共ab种可能,de位任取,故共有ab*1000种可能。 当c > 1时,ab位可以取0到ab共ab+1种可能,de任取,故共有 (ab + 1)* 1000种可能。