【PAT (Advanced Level)】1049. Counting Ones (30)
来源:互联网 发布:湖南工业大学的网络 编辑:程序博客网 时间:2024/05/22 10:37
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:12Sample Output:
5
我的做法是,可以按照数的位一位一位求该位所贡献的‘1’的个数;
例如:
12 --> '1'贡献了3次,'2'贡献了2次,所以一共有5个‘1’;
203 --> ‘2’贡献了100次,‘0’贡献了20次,‘3’贡献了21次,所以一共有141个‘1’;
规律其实很简单,个位每10次贡献1个‘1’,十位每百次贡献10个‘1’,百位每千次贡献100个‘1’...依此类推;
利用上诉规律不难写出相应的算法实现,但是要注意的是,没有达到贡献周期的位,要判断该位是否大于1(即是否超过贡献周期);
例如:
‘12’ 中的‘1’因为没有超过贡献周期,所以只贡献了3个‘1’(即‘10’、‘11’、‘12’中十位的‘1’)而不是10个,而‘2’因为超过了贡献周期中的分界,所以贡献了2个‘1’(即‘1’、‘11’中个位的‘1’);
具体实现代码如下:
/************************************This is a test program for anythingEnjoy IT!************************************/#include <iostream>#include <iomanip>#include <algorithm>#include <vector>#include <list>#include <set>#include <fstream>#include <string>#include <cmath>using namespace std;int main(){//ifstream cin;//cin.open("in.txt");//ofstream cout;//cout.open("out.txt");//////////////////////////////////////////////////////////////////////////// TO DO Whatever You WANT!int n;while (cin >> n){int sum = 0;int base = 1; // 基数,用来记录第几位int m = n;while (n != 0) // 每次去掉一位低位{int temp = n / 10;if (n % 10 > 1) // 如果准备去掉的低位大于1,则加上当前位置的基数sum += base;else if (n % 10 == 1) // 如果地位等于1,则加上原数尾部的个数sum += m % base + 1;sum += temp * base; // 当前位置所经过的轮数base *= 10; // 基数增长n /= 10; // 去掉低位}cout << sum << endl;}//////////////////////////////////////////////////////////////////////////// system("pause");return 0;}
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- 【PAT】【Advanced Level】1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- Pat(Advanced Level)Practice--1049(Counting Ones)
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- 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 Advanced Level】1004. Counting Leaves (30)
- PAT (Advanced Level) 1004. Counting Leaves (30)
- 【PAT】【Advanced Level】1004. Counting Leaves (30)
- HDU1245:Saving James Bond(Floyd)
- php 简单的二分法查找
- 在C#中使用官方驱动操作MongoDB
- springMVC学习笔记二(dispatcherServlet)
- 关于网上盛传的iPhone锁屏界面的设计
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- Linux命令 tail 加过滤功能
- sgu111 (大整数开方)
- Android开发之发送邮件功能的实现(源代码分享)
- RTMP/RTP/RTSP/RTCP的区别
- springMVC学习笔记三(controller控制器)
- POJ 1185 炮兵阵地 HDU 4539 郑厂长系列故事——排兵布阵
- UVA - 340 Master-Mind Hints
- TC流量控制实现分析(初步)