版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/89045956
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.
Each input file contains one test case which gives the positive N (≤230).
For each test case, print the number of 1's in one line.
12
5
我一开始的思路就是暴力破解,无脑将1~N转换成字符串,然后无脑for-each来数字符'1'出现的次数,果不其然?直接TLE!30分只得22分。
#include <bits/stdc++.h>
using namespace std;
int count1(int n) //用来数从1到n出现了几个1
{
int cnt = 0;
for(int i = 1; i <= n; i++)
{
string temp = to_string(i);
for(auto it : temp)
{
if(it == '1')
{
cnt++;
}
}
}
return cnt;
}
int main()
{
int N;
cin >> N;
cout << count1(N) << endl;
return 0;
}