大整数加法

来源:互联网 发布:风险评估矩阵中 编辑:程序博客网 时间:2024/06/16 13:33

6:大整数加法

  • 查看
  • 提交
  • 统计
  • 提问
总时间限制: 
1000ms 
内存限制: 
65536kB
描述

求两个不超过200位的非负整数的和。

输入
有两行,每行是一个不超过200位的非负整数,可能有多余的前导0。
输出
一行,即相加后的结果。结果里不能有多余的前导0,即如果结果是342,那么就不能输出为0342。
样例输入
2222222222222222222233333333333333333333
样例输出
55555555555555555555
来源
程序设计实习2007
  • 查看 
  • 提交 
  • 统计 
  • 提问using namespace std;
    #include<iostream>
    #include<iomanip>
    #include<stack>
    #include<string>
    int main()
    {
    stack<int> a, b, c;
    int f;
    int flag=0;
    string g,m;
    getline(cin,g);
    auto p = g.begin();
    while (p!=g.end())
    {
    f = *p-'0';
    a.push(f);
    p++;
    }
    getline(cin, m);
    p =m.begin();
    while (p != m.end())
    {
    f = *p-'0';
    b.push(f);
    p++;
    }
    while ((a.size() != 0) && (b.size() != 0))
    {
    f = a.top() + b.top() + flag;
    if (f >= 10)
    flag = 1;
    else flag = 0;
    c.push((f) % 10);
    a.pop();
    b.pop();
    }
    while (!a.empty())
    {
    f = a.top() + flag;
    if (f >= 10)
    flag = 1;
    else flag = 0;
    c.push((f) % 10);
    a.pop();
    }
    while (!b.empty())
    {
    f = b.top() + flag;
    if (f >= 10)
    flag = 1;
    else flag = 0;
    c.push((f) % 10);
    b.pop();
    }
    if (flag == 1)
    c.push(1);
    while ((!c.empty())&&(c.top() == 0))
    c.pop();
    if (c.empty())
    cout << 0;
    while (!c.empty())
    {
    f = c.top();
    cout << f;
    c.pop();
    }return 0;
    }
    • 虽然只是第六题,但应该算是堆栈的典型应用了,代码略长,不知道哪里可以精简一下
全局题号
1982
提交次数
190
尝试人数
58
通过人数
50

你的提交记录

#结果时间4Accepted05-083Runtime Error05-082Wrong Answer05-081Wrong Answer05-08
0 0
原创粉丝点击