PAT 1049. Counting Ones (30)
2015-08-21 22:25
429 查看
1049. Counting Ones (30)
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
#include <iostream> #include <cmath> #include <string> using namespace std; int ToInt(string num) { int res = 0; for (int i = 0; i < num.size(); i++) res = res * 10 + num[i] - '0'; return res; } int CountingOnes(string num) { if (num.size() == 1) { if (num == "0") return 0; else return 1; } else { int total = 0; int first = num[0] - '0'; string sub = string(num.begin() + 1, num.end()); if (first == 1) total += (ToInt(sub) + 1); else if (first > 1) total += pow(10, sub.size()); total += CountingOnes(sub) + first * CountingOnes(string(sub.size(), '9')); return total; } } int main() { string num; cin >> num; cout << CountingOnes(num); }
相关文章推荐
- linux下目录及终端学习
- UML类图关系
- Power Network 网络流入门题)
- 20150821日报
- Selenium 高阶应用之WebDriverWait 和 expected_conditions
- hdu 5406 CRB and Apple(树状数组+dp)
- w2k3企业版与w2k3 R2企业版
- 随机数大揭秘
- 初读《围城》
- 检查二叉树是否平衡
- EntityFramework之DetectChanges's Secrets(三)(我为EF正名)
- 闭包作用
- 读博文有感
- js的DOM(节点属性)
- Centos 6.6 创建桌面图标
- The Doors 最短路 + 简单几何
- OC学习--<猜拳游戏> 之 通过面向对象思想实现 2.0版本
- 近期学习计划
- 将博客搬至CSDN
- hdu1532Drainage Ditches裸的网络流