[编程题]整数加法

[编程题]整数加法

请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error

输入描述:
输入为一行,包含两个字符串,字符串的长度在[1,100]。

输出描述:
输出为一行。合法情况输出相加结果,非法情况输出error

示例1
输入
123 123
abd 123

输出
246
Error


想法:这个题很麻烦,因为在C++中,即便是long也最多只能存下64bit,而输入可能是100位十进制数字。因此这道题的思路应该是字符串的处理。
输入两个字符串a,b,分别将两个字符串的每一位两两相加,超过10则有进位,每一次计算结果保存在栈中。最后所有的结果加起来就是答案。


C++代码:

using namespace std;
bool exam(string a)
{
    for (int i = 0; i < a.size(); i++)
    {
        if ('0' < a[i] && a[i]<'9')
            continue;
        else
        {
            return false;
        }
    }
    return true;
}
string add0(string a, int num)
{
    for (int i = 0; i < num; i++)
    {
        a = "0" + a;
    }
    return a;
}
string add(string a,string b)
{
    string final;
    int times;
    if (a.size() > b.size())
    {
        times = a.size();
        b = add0(b, a.size() - b.size());
    }
    else
    {
        times = b.size();
        a = add0(a, b.size() - a.size());
    }
    int c = 0;
    for (int i = times-1; i >= 0; i--)
    {
        char temp_a = a[i];
        char temp_b = b[i];
        int result = stoi(&temp_a) + stoi(&temp_b)+c;
        if (result > 10)
        {
            c = 1;
            result = result % 10;
        }
        else
        {
            c = 0;
        }
        string temp = to_string(result);
        final = temp + final;
    }

    if(c==1)
        final = "1" + final;
    return final;
}
int main()
{
    string a, b;
    cin >> a >> b;
    if (exam(a) && exam(b))
    {
        cout << add(a,b) << endl;
    }
    else
    {
        cout << "error" << endl;
    }
}



其他人用的Python代码:
这里写图片描述


结论:教练,我要学Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值