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

本文介绍了一种高效算法来计算从1到给定正整数N中所有数字中1出现的次数。通过分析每一位上的规律,避免了直接遍历的方法,从而解决了大范围内的计数问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值