PAT.1049. Counting Ones (30)

原题地址:https://www.patest.cn/contests/pat-a-practise/1049
题目原文:

  1. Counting Ones (30) 时间限制 10 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

本来是用树状数组来写的,有两个点会超时,后来用写出来的程序测试了一些数据,发现结果存在一些递归规律。
以212为例,212其实就是将0~99数两遍,再从0数到12,这三遍的不同之处在于,第二遍里的首位是1,也就是说,第二遍数出来的结果要加上数的数的个数。现在的问题变成了数0~99, 0~12,通过数据测试发现,0~9, 0~99, 0~999……的1的个数分别问1, 20, 300……存在明显的规律,事先计算出存在数据中,现在问题变成了数0~2,数个位数时,若该数大于等于1,返回1,否则为0.
下面是AC的代码

#include<cstdio>
#include<sstream>
#include<string>
#include<vector>
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;

int lee[15];   //用于存储事先计算好的数据,lee[i]表示从0数到10*i - 1所含的1

int mpow(int cur)
{
    int res = 1;
    for (int i = 0; i < cur; i ++)
    {
        res *= 10;
    }
    return res;
}

int han(const string& cur)
{
    if(cur.size() == 0)
    return 0;
    else if(cur.size() == 1)
    {
        if(cur[0] >= '1')
        return 1;
        else
        return 0;
    }
    stringstream ss;
    int res = lee[cur.size() - 1];
    int n = atoi(cur.substr(1, cur.size() - 1).c_str());
    ss << n;
    if(cur[0] > '1')
    {
        return mpow(cur.size() - 1) + res * (cur[0] - '0') + han(ss.str());
    }else if(cur[0] == '1'){
        return res * (cur[0] - '0') + han(ss.str()) + n + 1;
    }   

}
int main()
{
    string sn;
    cin >> sn;
    for (int i = 1; i < 15; i ++)
    lee[i] = i * mpow(i - 1);
    int res = han(sn);
    cout << res << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值