PAT甲级1049(数1)

1049 Counting Ones (30 point(s))

  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

解题思路

  这个题我没做出来,看的算法笔记的思路
从低位到高位枚举每一位数字,同时得到当前数字左边数字的值left和右边数字的值right。如果当前数字为0,则当前位出现1的次数为左边0~left-1=left乘a;若当前数字为1,则当前位出现1的次数为left*a+right+1;若当前数字大于1,则当前位出现1的次数为(left+1)*a,详见代码

代码

#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>

//此题采用暴力法很显然会超时,直接累加每个位置上出现1的次数即可得最终结果

int main()
{
	int N;
	int ret = scanf("%d", &N);
	int left, now, right, res = 0, a = 1;//left代表当前数字左边的值,right代表右边的值,now代表当前数字
	while (N / a) {		
		left = N / (a * 10);
		now = N / a % 10;
		right = N % a;
		if (now == 0) {//如果当前数字等于0,则当其左边0到left-1,及其右边随便取值都可使当前位置为1
			res += left * a;
		}
		else if (now == 1) {//如果当前数字为1,左边0到left-1及右边随便取值加上当前位为1时,右边可取0到right
			res += left * a + right + 1;
		}
		else res += (left + 1) * a;//如果当前数字大于1,左边0到left及右边随便取值
		a *= 10;
	}
	printf("%d", res);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值