东华OJ-基础题-106-大整数相加(C++)

  • 问题描述
    I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
  • 输入说明
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
  • 输出说明
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
  • 输入范例
cpp 复制代码
2
1 2
112233445566778899 998877665544332211
  • 输出范例
cpp 复制代码
Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

感想:定义一个包含A与B的结构体,定义一个使用该结构体的vector,对vector里的A与B相加进行计算即可;注意输出的+左右两边得有空格,= 左右两边也得有空格,要不然PE。
代码如下:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

struct add {
    string a;
    string b;
};

int main() {
    int n;
    cin>>n;
    vector<add> arr(n);
    for(int i = 0; i<n; ++i) {
        cin>>arr[i].a>>arr[i].b;
    }

    for(int i =0; i<n; ++i) {
        string temp_a = arr[i].a,temp_b = arr[i].b;
        string ans;
        int j = temp_a.size();
        int k = temp_b.size();
        int carry = 0,add;
        while(j&&k) {
            add = (temp_a[--j]-'0')+(temp_b[--k]-'0')+carry;;
            carry = add/10;
            ans = to_string(add%10)+ans;
        }
        while(j) {
            add = (temp_a[--j] -'0' )+ carry;
            carry = add/10;
            ans = to_string(add%10)+ans;
        }
        while(k) {
            add = (temp_a[--k] -'0' )+ carry;
            carry = add/10;
            ans = to_string(add%10)+ans;
        }

        if(carry) ans = to_string(carry) + ans;
        if(i>0) cout<<endl;
        cout<<"Case "<<i+1<<":"<<endl;
        cout<<arr[i].a<<" + "<<arr[i].b<<" = "<<ans<<endl;

    }

    return 0;
}
相关推荐
沐知全栈开发17 分钟前
CSS Text(文本)
开发语言
会编程的土豆20 分钟前
【日常做题】 代码随想录(岛屿最大面积+寻宝)
数据结构·算法·图论
前进吧-程序员22 分钟前
现代 C++ 异步编程:从零实现一个高性能 ThreadPool (C++20 深度实践)
开发语言·c++·c++20
阿洛学长26 分钟前
汉洛塔结构思维
算法
木子n132 分钟前
第2篇:坐标变换与数学基础:FOC算法的核心数学工具
算法·电机控制·foc
Rsun0455135 分钟前
10、Java 桥接模式从入门到实战
java·开发语言·桥接模式
jieyucx44 分钟前
Golang 完整安装与 VSCode 开发环境搭建教程
开发语言·vscode·golang
阿Y加油吧1 小时前
两道经典 DP 题:零钱兑换 & 单词拆分(完全背包 + 字符串 DP)
算法
pearlthriving1 小时前
c++当中的泛型思想以及c++11部分新特性
java·开发语言·c++
疯狂打码的少年1 小时前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?
数据结构·算法·链表