[PAT A1049]Counting Ones
题目描述
1049 Counting Ones (30 分)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.
输入格式
Each input file contains one test case which gives the positive N (≤230).
输出格式
For each test case, print the number of 1’s in one line.
输入样例
12
输出样例
5
解析
- 题目大意很简单,就是说给一个正数N,要你计算从1到N的1的个数,比如12,那么有1,10,11,12,共有5个1.
- 这题暴力枚举是肯定不行的,如果暴力枚举有两个点是过不了的,当然也可以选择拿22分跑路,剩下的时间留着做其他的题也不错hhh。
- 主要思路就是找规律了,这里用晴神算法笔记里面的样例:
30710这个数:
首先考虑末尾为0,我们计算末尾有多少个数是覆盖了1的,那么末尾为1的时候前面是只能取0-3070,因为如果取3071,那么就是30711>30710了,共有3071种选择
然后考虑第二位1,它定死为1,那么前面为0-306的时候,后面一位随便取都行,当前面为307时,前四位为3071,末尾只能取0,那么有306*10+1种取法
然后考虑第三位,它为7,如果它为1的话,前面后面都可以随便取,因为它为7比1要大,只要他们组成的数不大于30710,都是有效的,那么取法共有(30+1)*102种
同理第四位为0,那要令它为1,前面只能取0-2,后面可以任取,共有3*103种
最后第五位,它是3,比1要大,所以它为1时,后面可以任取,共有104种
所以我们可以总结出,如果把某个数左边取为left,右边取为right,那么得到的结果有三种可能,a是right的位数次方(例如right=123,那么就是1000):
1.当前位为0,ans+=lefta;
2.当前位为1,ans+=lefta+right;
3.当前为>1,ans+=(left+1)*a
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int main()
{
string str;
int cnt = 0;
cin >> str;
int len = str.length();
if (len == 1) printf("1");
else {
if (str[0] == '1') cnt += stoi(str.substr(1)) + 1;
else cnt += pow(10, len - 1);
if (str[len - 1] == '0') cnt += stoi(str.substr(0, len - 1));
else cnt += stoi(str.substr(0, len - 1)) + 1;
for (int i = 1; i < len - 1; i++) {
string left = str.substr(0, i), right = str.substr(i + 1);
if (str[i] == '0') cnt += stoi(left)*pow(10, right.length());
else if (str[i]=='1') cnt += stoi(left)*pow(10, right.length()) + stoi(right) + 1;
else cnt += (stoi(left) + 1)*pow(10, right.length());
}
printf("%d", cnt);
}
return 0;
}