PAT甲级刷题记录——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.

Input Specification:

Each input file contains one test case which gives the positive N (≤2​30​​ ).

Output Specification:

For each test case, print the number of 1’s in one line.

Sample Input:

12

Sample Output:

5

思路

千万不要被题干的【The task is simple】所骗了,这题涉及的数学思想还是很变态的(我自认为在临场考试的时候是绝对想不出来的),如果暴力枚举,那么恭喜你,你能拿22分,并且花费的时间也就十分钟左右(算上读题目),如果想完全AC,不好意思,这题要思考的东西有很多。

这里我就不详细证明了,思路参考了【6号楼下的大懒喵】的结论:
PAT甲级刷题记录——1049 Counting Ones (30分)_第1张图片

代码

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    string tmp;
    cin>>tmp;
    int cnt = 0;
    int a, now, left, right;
    for(int i=tmp.length()-1, j=0;i>=0, j<tmp.length();i--, j++){
        a = pow(10, j);
        now = tmp[i]-'0';
        if(i==0) left = 0;
        else{
            string tmpleft = tmp.substr(0,i);
            left = stoi(tmpleft);
        }
        if(i==tmp.length()-1) right = 0;
        else{
            string tmpright = tmp.substr(i+1);
            right = stoi(tmpright);
        }
        if(now==0) cnt += left*a;
        else if(now==1) cnt += left*a+right+1;
        else cnt += (left+1)*a;
    }
    cout<<cnt;
    return 0;
}

你可能感兴趣的:(PAT甲级)