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
思路
从低位到高位考虑每一位为 1 的个数,设当前位的数为 i,该位左边的数为 leftNum,右边的数为 rightNum,e 从 1 开始每次遍历乘 10。通过数字举例,可以总结出这样的公式:
- i > 1 时,个数为 (leftNum + 1) * e
- i == 1 时,个数为 leftNum * e + rightNum + 1
- i == 0 时,个数为 leftNum * e
#include <cstdio>
int main() {
int n;
scanf("%d", &n);
int i, leftNum = n, rightNum, e = 1, ans = 0;
while (leftNum != 0) {
i = n / e % 10;
leftNum /= 10;
rightNum = n % e;
if (i > 1) {
ans += (leftNum + 1) * e;
} else if (i == 1) {
ans += leftNum * e + rightNum + 1;
} else {
ans += leftNum * e;
}
e *= 10;
}
printf("%d", ans);
return 0;
}