题目描述
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
思路
(见上篇,是上篇代码的优化)添加链接描述
实现
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string addStrings(string num1, string num2)
{
string str;
if (num1 == "0")
{
str = num2;
}
else if (num2 == "0")
{
str = num1;
}
else
{
int m = num1.size();
int n = num2.size();
int carry = 0;
int i = m - 1, j = n - 1;
for (; i >= 0 || j >= 0; i--, j--)
{
int m = i >= 0 ? num1[i] - '0' : 0;
int n = j >= 0 ? num2[j] - '0' : 0;
int temp = m + n + carry;
carry = temp / 10;
temp = temp % 10;
str.push_back(temp + '0');
}
if (carry == 1)
{
str.push_back('1');
}
reverse(str.begin(), str.end());
}
return str;
}
int main()
{
string str = addStrings("1", "9");
cout << str;
return 0;
}