【PAT (Advanced Level)】1049. Counting Ones (30)
2014-08-06 13:54
417 查看
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 anything
Enjoy 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)
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT 1049. Counting Ones (30)(数位dp(记忆化搜索))
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 解题报告 1049. Counting Ones (30)
- PAT (Advanced Level) 1115. Counting Nodes in a BST (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- 【PAT】【Advanced Level】1115. Counting Nodes in a BST (30)
- pat 1049. Counting Ones (30)
- pat 甲级 1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1115 Counting Nodes in a BST (30)
- PAT 1049. Counting Ones (30)(计算1到N,这些数字中1出现的个数,before i after,归纳)
- PAT_A 1049. Counting Ones (30)