F - Simple Addition UVA - 10994

Lets define a simple recursive function F(n), where
F(n) = p(x) =



n%10, if (n%10) > 0
0, if n = 0
F(n/10), Otherwise
Lets define another function S(p, q),
S(p, q) = ∑q
i=p
F(i)
In this problem you have to Calculate S(p, q) on given value of p and q.
Input
The input file contains several lines of inputs. Each line contains two non negative integers p and q
(p ≤ q) separated by a single space. p and q will fit in 32 bit signed integer. In put is terminated by a
line which contains two negative integers. This line should not be processed.
Output
For each set of input print a single line of the value of S(p, q).
Sample Input
1 10
10 20
30 40
-1 -1
Sample Output
46
48
52

#include <stdio.h>
typedef long long ll;
ll ans;
 
ll f(ll x) {
	if (x == 0)	return 0;
	else if (x % 10)
		return x % 10;
	else 
		return  f(x / 10);
}
 
void solve(ll l, ll r) {
	if (r - l < 9) {
		for (int i = l; i <= r; i++)
			ans += f(i);
		return;
	}
	
	while (l % 10) {
		ans += f(l);
		l++;
	}
 
	while (r % 10) {
		ans += f(r);
		r--;
	}
	ans += 45 * (r - l) / 10;
	solve(l / 10, r / 10);
}
 
int main () {
	ll l, r;
	while (scanf("%lld%lld", &l, &r), l >= 0 || r >= 0) {
		ans = 0;
		solve(l, r);
		printf("%lld\n", ans);
	}
	return 0;
}

上面这个是看了别的大神得到的
下面这个是自己写的,但超时了

#include <iostream>
using namespace std;
typedef long long ll;

ll f(int n){
	if(n%10>0)	return n%10;
	else if(n==0)	return 0;
	else return f(n/10);
}

void S(int p, int q){
	int sum=0;
	for(int i=p; i<=q; i++){
		sum+=f(i);
	}
	cout<<sum<<endl;
}

int main(){
	ll x,y;
	
	do{
		cin>>x>>y;
		if(y-x>=9)	S(x,y);
		else{
			int sum=0;
			for(int i=x; i<(x/10+1)*10; i++)				sum+=f(i);	//开始的数到第一个整十数 
			for(int i=(x/10+1)*10; i<=(y/10)*10; i*=10)		sum+=f(i); 		//整十的数字 
			for(int i=(y/10)*10+1; i<=y; i++)	sum+=f(i);		//最后一个整十数到结束 
			int t=y/10-x/10-1;
			sum+=t*45;
			cout<<sum<<endl;
		}
	}while(x>=0&&y>=0);
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值