您的位置:首页 > 其它

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

2017-08-05 19:10 453 查看


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: