【PAT】【Advanced Level】1049. Counting Ones (30)

来源:互联网 发布:河北大学工商学院 知乎 编辑:程序博客网 时间:2024/06/14 09:25

1049. Counting Ones (30)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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
原题链接:

https://www.patest.cn/contests/pat-a-practise/1049

https://www.nowcoder.com/pat/5/problem/4088

思路:

占坑写题解。。。

CODE:

#include<iostream>#include<cstring>#include<string>#include<cstdio>#include<cstdlib>using namespace std;int main(){string a;cin>>a;int re=0;long long sum=0;long long te=1;for (int i=a.length()-1;i>=0;i--){if (a[i]-'0'==0) {re+=( atoi(a.substr(0,i).c_str())*te );}else if(a[i]-'0'==1) {re+=( atoi(a.substr(0,i).c_str())*te + sum +1);}else{re+=( (atoi(a.substr(0,i).c_str())+1)*te );}//cout<<re<<endl;sum+=te*(a[i]-'0');te*=10;}cout<<re;return 0;}


原创粉丝点击