前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【PAT甲级】Counting Ones

【PAT甲级】Counting Ones

作者头像
喜欢ctrl的cxk
发布2019-11-08 14:12:29
2760
发布2019-11-08 14:12:29
举报
文章被收录于专栏:Don的成长史Don的成长史

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_42449444/article/details/89045956

Problem Description:

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:

代码语言:javascript
复制
12

Sample Output:

代码语言:javascript
复制
5

解题思路:

我一开始的思路就是暴力破解,无脑将1~N转换成字符串,然后无脑for-each来数字符'1'出现的次数,果不其然?直接TLE!30分只得22分。

AC代码: TLE代码:

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem Description:
  • Input Specification:
  • Output Specification:
  • Sample Input:
  • Sample Output:
  • 解题思路:
  • AC代码: TLE代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档