文章
9
粉丝
1
获赞
124
访问
2.3k
思路:字符串存储 a ,b ,输出字符串 result ,对 a b 从各自的最后一位进行加,得到的结果 temp = anum + bnum + carry; 将其余数加入到 result 中, carry = temp / 10;
注意点:判断条件是 a b 或者 carry 都不为零。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string addStr(string a, string b){
string result;
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
// 前两个条件用于不等长的 a b, carry > 0 用于 9 + 1 = 10 的情况
while(i >= 0 || j >= 0 || carry > 0){
int anum = i >= 0 ? a[i] - '0' : 0;
int bnum = j >= 0 ? b[j] - '0' : 0;
int temp = anum + bnum + carry;
result.push_back('0' + (temp % 10));
carry = temp / 10; // 只会有 0 或者 1
i--;
j--;
}
reverse(result.begin(), result.end());
return result;
}
int main(){
string a,b;
while(cin >> a >> b){
string result = addStr(a,b);
cout << result << endl;
...
登录后发布评论
暂无评论,来抢沙发