1049 Counting Ones
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
代码
22分代码
如果to_string 不可用点击如下链接
https://blog.csdn.net/weixin_44635198/article/details/114404887
#include<bits/stdc++.h>
using namespace std;
int main(){
size_t n;
string str;
cin >> n;
for(size_t i=1; i<=n; i++) {
str += to_string(i);
}
cout << count(str.begin(),str.end(),'1');
return 0;
}