PAT甲级A1049 Counting Ones (30 分)

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 (≤2​30​​).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:

12

Sample Output:

5

题意:给定一个数n,让你数出从1到n所有数字中‘1’出现的次数。

思路:依次算出n的个位十位百位等每个位置上1的个数累加即可。每个位置上1的次数与当前位cur及高位部分high及低位部分low都有关系,同时当前位cur为0,1及其他情况1出现的次数也不同。

          例如n=256时,个位上1出现26次 。十位上1出现:2*10+10=30次,百位上1出现:1*100=100次;

当n=216时,十位上,当前位cur=1,high=2,low=6,此时十位上出现次数为high*10+low+1

当n=206时,十位上,当前位cur=0,high=2,low=6,此时十位上出现次数为high*10;

参考代码:

#include<cstdio>
using namespace std;
int solve(int n){
	int cnt=0,factor=1;
	while(n/factor>0){
		int high=n/(factor*10);
		int low=n-n/factor*factor;
		int cur=n/factor%10;		//求当前位的数字
		if(cur==0) cnt+=high*factor;
		else if(cur==1) cnt+=high*factor+low+1;
		else cnt+=high*factor+factor;
		factor*=10;
	}
	return cnt;
}
int main()
{
	int n;
	scanf("%d",&n);
	printf("%d\n",solve(n));
	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值