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; }