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
solution:
1049. Counting Ones (30)-PAT甲级真题(数学问题) – 柳婼 の blog
#include <iostream>
using namespace std;
int main() {
int n, left = 0, right = 0, a = 1, now = 1, ans = 0;
scanf("%d", &n);
while(n / a) {
left = n / (a * 10), now = n / a % 10, right = n % a;
if(now == 0) ans += left * a;
else if(now == 1) ans += left * a + right + 1;
else ans += (left + 1) * a;
a = a * 10;
}
printf("%d", ans);
return 0;
}
看之前一点头绪都没有,做个笔记方便之后哪天忘记了可以看看
当前now==0时,left*a代表左侧数字从0~left-1时可以。比如数字201,对于十位数0,那么此时十位数上数字为2*10,即010,011,012,013...019,110,111,112...,119,共2*10个。
若now==1时,在以上基础上还要考虑right从0~right,即right+1,例如数字212,对于十位数字1,除去上述数字010,011,012,013...019,110,111,112...,119,还有210,211,212三个数字,也就是在考虑左侧0~left-1基础上多考虑右侧0~right。
其他now>=2时,就是在now==0的基础上,即左侧0~left-1可以多考虑letf,即0~left,例如121,如果是101的话只能考虑010,011,012...019十个,但是121可以多考虑110,111,112...119这十个,得益于十位数超过1,而131,141,151...191,在十位数上1的个数上,与121相同。
大概思路到此。插眼