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);
}