PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数

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
题目的时间限制是10ms,若用遍历的方法检测从1到n每个数中1的个数,在n较大时肯定会超时。
对于n的每一位,可以分为该位为0,该位为1,和该位大于1三种情况讨论。
考虑n=15042的百位,由于百位是0,1到n中百位能否为1仅由更高的两位15决定,这两位可以是00到14,即001XX、011XX...141XX,低位XX可以是00到99,故满足条件的共15*100=1500个数。
考虑n=15142的百位,由于百位是1,在上例15042的基础上,低位42贡献了151XX,XX可以是00到42,共43个数,故满足条件的有15*100+42+1=1543个数。
考虑n=15242的百位,由于百位大于1,在第一个例子15042的基础上,增添了151XX,XX可以是00到99,故满足条件的有(15+1)*100=1600个数。
对于n的每一位,都可以通过分析该位数字,以及高位和低位数字,来得到从1到n中该位出现1的次数。
/*2015.7.26cyq*/
#include <iostream>
using namespace std;

int main(){
	int n;
	cin>>n;
	int cur,low,high;
	int count=0;
	int base=1;
	while(n/base){
		low=n%base;		//低位
		cur=n/base%10;	//当前位
		high=n/base/10;	//高位
		switch(cur){
		case 0:
			count+=high*base;
			break;
		case 1:
			count+=high*base+low+1;
			break;
		default:
			count+=(high+1)*base;
			break;
		}
		base*=10;
	}
	cout<<count<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值