1049 Counting Ones (30 point(s))
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
题目大意
给定一个数字N,要求你计算从1-N的所有数字中出现了多少个1
解题思路
这个题我没做出来,看的算法笔记的思路
从低位到高位枚举每一位数字,同时得到当前数字左边数字的值left和右边数字的值right。如果当前数字为0,则当前位出现1的次数为左边0~left-1=left乘a;若当前数字为1,则当前位出现1的次数为left*a+right+1;若当前数字大于1,则当前位出现1的次数为(left+1)*a,详见代码
代码
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
//此题采用暴力法很显然会超时,直接累加每个位置上出现1的次数即可得最终结果
int main()
{
int N;
int ret = scanf("%d", &N);
int left, now, right, res = 0, a = 1;//left代表当前数字左边的值,right代表右边的值,now代表当前数字
while (N / a) {
left = N / (a * 10);
now = N / a % 10;
right = N % a;
if (now == 0) {//如果当前数字等于0,则当其左边0到left-1,及其右边随便取值都可使当前位置为1
res += left * a;
}
else if (now == 1) {//如果当前数字为1,左边0到left-1及右边随便取值加上当前位为1时,右边可取0到right
res += left * a + right + 1;
}
else res += (left + 1) * a;//如果当前数字大于1,左边0到left及右边随便取值
a *= 10;
}
printf("%d", res);
return 0;
}