C++ 大数相加

#include "stdafx.h"
#include
#include
using namespace std;

int main()
{
    stack<char> data1;
    stack<char> data2;
    char ch = 0;
    while ((cin.peek() != EOF) && (cin.peek() != '\n') && (cin.peek() != ' '))
    {
        cin >> ch;
        data1.push(ch);
    }
    do
    {
        cin >> ch;
        data2.push(ch);
    } while ((cin.peek() != EOF) && (cin.peek() != '\n') && (cin.peek() != ' '));
    // 大数相加
    stack<char> result;
    int carry = 0;
    while (!data1.empty() || !data2.empty())
    {
        int d1 = 0;
        int d2 = 0;
        if (!data1.empty())
        {
            d1 = data1.top() - '0';
            data1.pop();
        }
        if (!data2.empty())
        {
            d2 = data2.top() - '0';
            data2.pop();
        }
        int ret = d1 + d2 + carry;
        carry = ret / 10;
        ret = ret % 10;
        result.push(ret+'0');
    }

    while (!result.empty())
    {
        cout << result.top();
        result.pop();
    }
    cout << endl;
    return 0;
}

这里写图片描述

你可能感兴趣的:(软件)