UVA10944 Simple Addition(递归)

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
5
•例如,求S(2,53),将范围划分为3个区间:[2,9][10,50][51,
53]。
•对于第1个区间[2,9],个位数之和2+3+4+...+9=44;对于第2个区
间[10,50],个位数之和(1+2+...+9)4=454=180;对于第3个区
间[51,53],个位数之和1+2+3=6。所以,第一轮,个位数的总和
为44+180+6=230。
•在[10,50]中,10,20,30,4050的个位数是0,将这些数除以10后
得1,2,3,4,5,产生新区间[1,5];进入第二轮,区间[1,5]中的数
只有个位数,个位数之和1+2+3+4+5=15。
•最后,两轮结果相加,得S(2,53)=230+15=245
#include <bits/stdc++.h>
#define ll long long
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;
}

猜你喜欢

转载自blog.csdn.net/qq_43738331/article/details/112856513