PAT (Advanced Level) 1049 Counting Ones (规律、思维)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w419387229/article/details/82192138

感觉这题完全就是一种思维题,范围2^{30},暴力根本不需要思考,所以跟1有关系的,就在于各个数位上,这样思路下来,推出以下关系:

1. 该位为0,只受高位影响,如203中的十位,只可能出现10~19,110~119

2.该位为1,受高位和低位影响,如213的十位,有10~19,110~119;213,212,211;不同分号间分别代表高位和地位影响,以及还有它自身210(其实也可以归在低位影响中)

3.该位大于1,则只受高位影响,如223中的十位,有10~19,110~119,210~219

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

int n;

int main(){
	scanf("%d",&n);
	int ans = 0, rad = 1, high, low, cur;
	while(n / rad > 0){
		high = n / (10 * rad);
		cur = n / rad % 10;
		low = n % rad;
//		printf("%d %d %d\n",high,cur,low);
		if(cur == 0)
			ans += high * rad;
		else if(cur == 1)
			ans += high * rad + low + 1;
		else
			ans += (high + 1) * rad;
		rad *= 10;
	}
	cout << ans << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/w419387229/article/details/82192138