PAT.1049. Counting Ones (30)
来源:互联网 发布:董秘助手软件下载 编辑:程序博客网 时间:2024/06/01 08:16
原题地址:https://www.patest.cn/contests/pat-a-practise/1049
题目原文:
- 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所含的1int 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
- 1049. Counting Ones (30)-PAT
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- PAT.1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones
- PAT 1049. Counting Ones
- PAT--1049. Counting Ones
- PAT Counting Ones (30)
- PAT A 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- 1049. Counting Ones (30) PAT甲级
- PAT甲级.1049. Counting Ones (30)
- PAT甲级练习1049. Counting Ones (30)
- AndrewNG-MachineLearning-Week1
- Handle机制详解
- poj 1401Factorial
- ffmpeg 的编译选项
- POJ 2342 Anniversary party树形dp
- PAT.1049. Counting Ones (30)
- mongodb命令批量插入json文件数据
- 云管理平台简介
- Spring AOP
- 谈图像处理
- iOS 到处 ipa包的时候 会有四个选项分别代表什么
- cocos2dx CCFileUtils::sharedFileUtils() 静态调用
- 线程池
- Phalcon使用PHPExecl导出导入Execl文件