描述
以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 计算两个数之和
* @param s string字符串 表示第一个整数
* @param t string字符串 表示第二个整数
* @return string字符串
*/
string solve(string s, string t) {
int i = s.length()-1;
int j= t.length()-1;
int add = 0;
string result="";
while (i >= 0 && j >= 0)
{
int temp = s[i] - '0' + t[j] - '0' + add;//字符串转数字后再进行相加
add = temp / 10;
result = to_string(temp % 10) + result;//int转字符串
--i;
--j;
}
while (i>=0)
{
int temp = s[i] - '0' + add;
add = temp / 10;
result = to_string(temp % 10) + result;//int转字符串
--i;
}
while (j >= 0)
{
int temp = t[j] - '0' + add;
add = temp / 10;
result = to_string(temp % 10) + result;//int转字符串
--j;
}
if (add != 0)
result = to_string(add) + result;
return result;
}
};