东华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;
}
相关推荐
小陈工1 小时前
Python安全编程实践:常见漏洞与防护措施
运维·开发语言·人工智能·python·安全·django·开源
John_ToDebug7 小时前
浏览器扩展延迟加载优化实战:如何让浏览器启动速度提升50%
c++·chrome·windows
是娇娇公主~7 小时前
C++ 中 std::deque 的原理?它内部是如何实现的?
开发语言·c++·stl
SuperEugene8 小时前
Axios 接口请求规范实战:请求参数 / 响应处理 / 异常兜底,避坑中后台 API 调用混乱|API 与异步请求规范篇
开发语言·前端·javascript·vue.js·前端框架·axios
Fly Wine8 小时前
Leetcode之有效字母异位词
算法·leetcode·职场和发展
xuxie998 小时前
N11 ARM-irq
java·开发语言
程序员夏末9 小时前
【LeetCode | 第七篇】算法笔记
笔记·算法·leetcode
wefly20179 小时前
从使用到原理,深度解析m3u8live.cn—— 基于 HLS.js 的 M3U8 在线播放器实现
java·开发语言·前端·javascript·ecmascript·php·m3u8
luanma15098010 小时前
PHP vs C++:编程语言终极对决
开发语言·c++·php
寂静or沉默10 小时前
2026最新Java岗位从P5-P7的成长面试进阶资源分享!
java·开发语言·面试