PAT甲级 1049 Counting Ones

原题链接:

https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805430595731456&page=0

注意点:

  1. 这道题需要找规律,可以使用打表法,即通过暴力的方法计算出当N比较小时的结果(我这里计算出来当N在0-299时对应的输出),通过大量数据寻找规律。
  2. 我这里的处理思路是从个位开始,计算小于等于N时,该位上为1的可能性。举例说明:当N为210,先看个位0,个位上为1小于等于210的有001,011,021,031,...,201,一共21个;再看十位1,十位上为1且小于等于210的有01_(010,011,...,019)(10个),11_(10个),210(1个);最后看百位2,百位上为1且小于等于210的有1__(100个)。21+10+10+1+100=142为最终输出。

代码:

#include <iostream>
using namespace std;

#define endl '\n'

int N;
//int cnt[300];
int res = 0;

//int findOne(int x) {
//	int res = 0;
//	while (x != 0) {
//		int last = x % 10;
//		x /= 10;
//		if (last == 1) {
//			res++;
//		}
//	}
//	return res;
//}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	cin >> N;
	/*for (int i = 1; i < 300; i++) {
		cnt[i] = cnt[i - 1] + findOne(i);
	}*/

	int source = N;
	int last = 0;
	int radix = 1;
	while (N != 0) {
		last = N % 10;
		N /= 10;
		res += N*radix;
		if (last > 1) {
			res += radix;
		}
		else if (last == 1) {
			res += source % radix + 1;
		}
		radix *= 10;
	}

	cout << res;
		
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值