PAT1049. Counting Ones (30)(数学)

题意:

给出一个n,求从0到n一共出现几个1

思路:

这题还是有点复杂的,看了一下别人的代码,基本思路是一位一位考虑,也就是计算这一位为1的数有几个,用now表示当前位的值,left为左边的数字,right为右边的数字,a为当前位的位数,以3105为例:

  • 当now>=2时,比如分为310 5 0,此时now=5也就是说可以取(0~310)1,这些数当前位为1,res+=(left+1)*a
  • 当now==1时,比如3 1 05,此时1后面的数不能取全到a,只能取到right,所以res+=left*a+right+1
  • 当now==0时,比如31 0 5,此时只能当(0~30)时当前位才能取1,所以res+=left*a
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<string.h>
#include<sstream>
#include<functional>
#include<algorithm>
using namespace std;
const int INF = 0xfffff;
const int maxn = 1050;

int main() {
	int n, left = 0, right = 0, now = 0, a = 1;
	scanf("%d", &n);
	int res = 0;
	while (n / a) {
		left = n / (a*10);
		right = n%a;
		now = n / a % 10;
		if (now == 0)	res += left*a;
		else if (now == 1)	res += left*a + right + 1;
		else res += (left + 1)*a;
		a *= 10;
	}
	printf("%d\n", res);
	return 0;
}

转载于:https://www.cnblogs.com/seasonal/p/10343624.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值