UVA 12517 Digit Sum

题意:给出两个数n,m,求n到m之间所有数字的所有数位上的数的和。

好久不做这类题思路总是很凌乱。具体看代码吧。

 1 #include <cstdio>
 2 typedef long long LL;
 3 LL dp(LL x){
 4     LL ret = 0;
 5     LL p[11];
 6     p[0] = 1;
 7     for(int i = 1;i <= 10;i++)
 8         p[i] = p[i-1]*10;
 9     int idx[11],cnt = 0;
10     while(x){
11         idx[cnt++] = x%10;
12         x /= 10;
13     }
14     int sum = 0;
15     for(int pos = cnt-1;pos >= 0;pos--){
16         for(int j = 0;j < idx[pos];j++){
17             ret += (sum+j) * p[pos];
18             if(pos) ret += (p[pos-1]*pos*45);
19         }
20         sum += idx[pos];
21     }
22     ret += sum;
23     return ret;
24 }
25 
26 int main(){
27     LL a,b;
28     while(scanf("%lld%lld",&a,&b),a+b){
29         printf("%lld\n",dp(b)-dp(a-1));
30     }
31 }
View Code

 

posted @ 2013-11-01 22:03  浙西贫农  阅读(210)  评论(0编辑  收藏  举报