【PAT (Advanced Level)】1049. Counting Ones (30)

来源:互联网 发布:湖南工业大学的网络 编辑:程序博客网 时间:2024/05/22 10:37

1049. Counting Ones (30)

时间限制
10 ms
内存限制
32000 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
这题意思很简单,就是让把从1~N所有经过的数中的‘1’的个数全部加起来。用遍历法可以求出,但有2个case会超时,这里就会涉及到一些优化或者发现规律;

我的做法是,可以按照数的位一位一位求该位所贡献的‘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;}


0 0
原创粉丝点击