題目1051:數字階梯求和 2010年哈爾濱工業大學計算機研究生機試真題

題目1051:數字階梯求和

時間限制:1 秒

內存限制:32 兆

特殊判題:

提交:4894

解決:1664

題目描述:

給定a和n,計算a+aa+aaa+a...a(n個a)的和。

輸入:

測試數據有多組,輸入a,n(1<=a<=9,1<=n<=100)。

輸出:

對於每組輸入,請輸出結果。

樣例輸入:
1 10
樣例輸出:
1234567900
來源:
2010年哈爾濱工業大學計算機研究生機試真題
#include <stdio.h>
#include <iostream>
typedef struct BigInt BigInt;
struct BigInt{
    int digit[1000];
    int size;
    void init(){
        for(int i=0;i<1000;i++){
            digit[i]=0;
        }
        size=0;
    }
    void set(int a,int n){
        init();
        int j=0,t=0,c=1;
        for(int i=n-1;i>=0;i--){
            t+=a*c;
            j++;c*=10;
            if(j==4||i==0){
                digit[size]=t;
                size++;j=0;t=0;c=1;
            }
        }
    }
    void output()
    {
        for(int i=size-1;i>=0;i--){
            if(i!=size-1)
                printf("%04d",digit[i]);
            else
                printf("%d",digit[i]);
        }
        printf("\n");
    }
    BigInt operator +(const BigInt &A)const{
        BigInt res;res.init();
        int carry=0;
        for(int i=0;i<A.size||i<size;i++){
            int tmp=A.digit[i]+digit[i]+carry;
            carry=tmp/10000;
            tmp%=10000;
            res.digit[res.size]=tmp;
            res.size++;
        }
        if(carry!=0){
            res.digit[res.size++]=carry;
        }
        return res;
    }
};
int main(){
    int a=0,n=0;
    while (~scanf("%d %d",&a,&n)){
        BigInt res,x;
        res.init();
        res.set(0,1);
        for(int i=1;i<=n;i++)
        {
            x.init();
            x.set(a,i);
            res=res+x;
        }
        res.output();
    }
    return 0;
}
/**************************************************************
    Problem: 1051
    User: 愛理momoko
    Language: C++
    Result: Accepted
    Time:0 ms
    Memory:1520 kb
****************************************************************/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章