Wednesday, April 6, 2011

Spoj_03032_Adding_two_numbers.cpp

Problem Links:

spoj03032,

Problem:

SPOJ Problem Set (tutorial)

3032. Adding two numbers

Problem code: ADUN

Your task is to read two numbers a and b (0 < a, b <2100000000) and to output their sum.

Input

Input contains two lines, on the first line the number a and on the second line the number b.

Output

Output the sum of the two numbers.

Example

Input:
20
30

Output:
50














Solution:

String implementation.

Source Code:

//Wed Apr  6 13:24:05 CDT 2011
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string add(string A, string B)
{
    reverse(A.begin(), A.end());
    reverse(B.begin(), B.end());
    string sum = "";
    int flag = 0;
    int i;
    for (i = 0; i < min(A.size(), B.size()); i++)
    {
        int tmp = (A[i] - '0') + (B[i] - '0') + flag;
        sum += '0' + tmp % 10;
        flag = tmp > 9 ? 1 : 0;
    }
    while (i < A.size())
    {
        int tmp = A[i] - '0' + flag;
        sum += '0' + tmp % 10;
        flag = tmp > 9 ? 1 : 0;
        i++;
    }
    while (i < B.size())
    {
        int tmp = B[i] - '0' + flag;
        sum += '0' + tmp % 10;
        flag = tmp > 9 ? 1 : 0;
        i++;
    }
    if (flag > 0)
        sum += '0' + flag;
    reverse(sum.begin(), sum.end());
    return sum;
}

int main(int argc, char* argv[])
{
    string A;
    string B;
    while (cin >> A >> B)
        cout << add(A, B) << endl;
    return 0;
}

No comments :