题目连接

题意:计算从a到b每个数每位数字相加的和

code:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef unsigned long long ll;
ll cnt[16];                                       //cnt[i]表示0 到 最大n位数的个位数的和 
ll s[16];                                         //s[i]表示10的i次方   
ll num[17];
ll cop[17];
void init(){
    ll base = 10;
    cnt[0] = 0;
    cnt[1] = 45;
    for(ll i = 2;i <= 16;i ++){
        cnt[i] = cnt[1] * base * i;
        base *= 10; 
    } 
    s[0] = 1;
    s[1] = 10;
    for(int i = 2;i <= 16;i ++){
        s[i] = 10 * s[i-1];
    } 
} 
ll getSum(ll a){
    ll count = 1;
    while(a){
        cop[count] = a%10;
        a /= 10;
        count ++;
    }
    count --;          //代表位数 
    for(ll i = 1;i <= count;i ++){
        num[i] = cop[count-i+1];
    }
    ll Sum = 0;
    ll ss = 0;
    for(ll i = 1;i <= count;i ++){
        Sum += (num[i])*cnt[count-i];
        for(ll j = 0;j < num[i];j ++){
            Sum += (ss + j)*s[count-i];
        }
        ss += num[i];
    }
    for(ll i = 1;i <= count;i ++) Sum += num[i]; 
    return Sum;
}
int main(void){
    init();
    ll cas;
    ll a,b;
    cin >> cas;
    while(cas --){
        cin >> a >> b;
        if(a == 0) a = 1;
        ll aa,bb;
        bb = getSum(b);
        aa = getSum(a-1);
        cout << bb - aa<< endl;
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/zhangjialu2015/p/5697119.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐