I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum o

本文介绍了一个使用C++实现的字符串加法程序,该程序能够处理任意长度的数字字符串相加,并展示了解决不同长度字符串间加法的具体算法细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>
using namespace std;
int main(void)
{
string add(string str1, string str2);
int n, i, j;
cin>>n;
string str1, str2, tstr1, tstr2;
for(i = 1; i <= n; i++)
{
cout<<"Case "<<i<<":\n";
cin>>str1>>str2;
tstr1 = str1;
tstr2 = str2;
int len1 = str1.length();
int len2 = str2.length();
if(len1 > len2)
{
for(j = 0; j < len1 - len2; j++)
{
str2 = "0" + str2;
}
}
else if(len1 < len2)
{
for(j = 0; j < len2 - len1; j++)
{
str1 = "0" + str1;
}
}
cout<<tstr1<<" + "<<tstr2<<" = "<<add(str1, str2)<<endl;
if(i != n) cout<<endl;
}
return 0;
}
string add(string str1, string str2)//字符串做算术加法的函数
{
bool flag = false;
string result = "";
int i;
for(i = str1.length() - 1; i >= 0; i--)
{
int a = str1[i] - '0';
int b = str2[i] - '0';
int sum = 0;
if(flag) sum = 1;
sum += (a + b);
if(sum / 10 > 0) flag = true;
else flag = false;
result = char(sum % 10 + 48) + result;
}
if(flag)
result = '1'+result;//如果有进位就在前面加上1
return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值