A+B Problem Plus [Medium]
题目描述
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
解答要求
时间限制:1000ms, 内存限制:100MB
输入
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.
样例
输入样例 1 复制
2
1 2
112233445566778899 998877665544332211
输出样例 1
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
反向打印与补零
这里在原数组正着一位一位的加上,同时注意超过的位数补全为0,之后输出时反向打印出来。
#define MAX_NUM 100
int BigNumberAdd(char *a, char *b, int *calcResult)
{
int lenA = strlen(a);
int lenB = strlen(b);
int carry = 0;
int resLen = 0;
while (lenA > 0 || lenB > 0 || carry > 0) {
int chA = lenA > 0 ? a[lenA - 1] - '0' : 0;
int chB = lenB > 0 ? b[lenB - 1] - '0' : 0;
int temp = chA + chB + carry;
carry = temp / 10;
calcResult[resLen++] = temp % 10;
lenA--;
lenB--;
}
return resLen;
}
int main()
{
int t;
if (scanf_s("%d", &t) == EOF) {
return 0;
}
int count = 0;
while (t--) {
char a[MAX_NUM];
char b[MAX_NUM];
if (scanf_s("%s%s", a, sizeof(a), b, sizeof(b)) == EOF) {
continue;
}
int calcResult[MAX_NUM];
int resLen = BigNumberAdd(a, b, calcResult);
count++;
printf("Case %d:\n", count);
printf("%s + %s = ", a, b);
for (int i = resLen - 1; i >= 0; i--) {
printf("%d", calcResult[i]);
}
printf("\n\n");
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】