SDNU 1126 Integer Inquiry

Description
One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
This supercomputer is great,'' remarked Chip.I only wish Timothy were here to see these results.” (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Sample Input

1

123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0

Sample Output

370370367037037036703703703670

思路:與上一題一樣,只是上一題只有兩個相加,而這一個是多個數存,將上一個該寫一下就行了,即每一個都是當前的數與之前所有數的和的和。

# include <cstdio>
# include <iostream>
# include <string>
using namespace std;
string add (string str1, string str2)
{
    string str;
    int len1 = str1.size();
    int len2 = str2.size();
    if (len1 > len2)//在短的那一個前邊補零,以便計算。
        for (int i=1; i<=len1-len2; ++i)
            str2 = '0' + str2;
    else
        for (int i=1; i<=len2-len1; ++i)
            str1 = '0' + str1;
    int t;
    int n=0;
    len1 = str1.size();
    for (int i=len1-1; i>=0; --i)
    {
        t = str1[i]-'0'+str2[i]-'0'+n;
        n = t / 10;
        t %= 10;
        str = char (t+'0') + str;
    }
    if (n != 0)
     str=char(n+'0')+str;
    return str;


}
int main ()
{
    int n;
    scanf ("%d",&n);
    while (n--)
    {
        string s = "0";
        string str;
        while (cin >> str)
        {
            if (str == "0")
                break;
            s = add(s,str);
        }
        cout << s << endl;
        if (n > 0)
        cout << endl;

    }

    return 0;
}
發佈了33 篇原創文章 · 獲贊 2 · 訪問量 7613
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章