大数相加(数值太大而不能用int定义)

示例输入

2

1 2

112233445566778899 998877665544332211

示例输出

Case 1:

1 + 2 = 3

Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

代码:
#include<iostream>
#include<string>
using namespace std;
string add(string s, string t)
 {
   //若是其中一个为空,返回另一个 fast-template
        if (s.empty())
            return t;
        if (t.empty())
            return s;
        //让s为较长的,t为较短的
        if (s.length() < t.length())
            swap(s, t);
        //进位标志
        int carry = 0;
        //从后往前遍历较长的字符串
        for (int i = s.length() - 1; i >= 0; i--) 
        {
            //转数字加上进位
            int temp = s[i] - '0' + carry;
            //转较短的字符串相应的从后往前的下标
            int j = i - s.length() + t.length();
            //如果较短字符串还有
            if (j >= 0)
                //转数组相加
                temp += t[j] - '0';
            //取进位
            carry = temp / 10;
            //去十位
            temp = temp % 10;
            //修改结果
            s[i] = temp + '0';
        }
        //最后的进位
        if (carry == 1)
            s = '1' + s;
        return s;
  }
void print(string s1, string s2, string s3, int i, int t) 
 {//格式输出

        cout << "Case " << i << ":" << endl;
        if (i != t)
            cout << s1 << " + " << s2 << " = " << s3 << endl << endl;
        else
            cout << s1 << " + " << s2 << " = " << s3 << endl;
 }

int main()
{
    int n;
    string s, t,he;
    while (cin>>n)
    {
        for (int i = 1; i <= n; i++)
        {
            cin >> s >> t;
            he = add(s, t);
            print(s, t, he, i, n);
        }
    }
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值