题目
链接:https://leetcode.com/problems/add-strings/discuss/
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
题意
给你两个字符串,返回字符串的和。
注意:
- 每个字符串的长度<5100。
- 字符串中只包含数字0~9。
- 字符串没有前导零。
- 不能使用大数库和直接转换字符串。
思路
把字符串逐个存入int数组中。
简单写法
class Solution {
public:
string addStrings(string num1, string num2)
{
int i = num1.size()-1, j = num2.size()-1, carry = 0, sum = 0 , temp;
string res="";
while(i>=0 || j>=0 || carry>0)
{
temp = carry;
if(i>=0)
temp += num1[i--]-'0';
if(j>=0)
temp += num2[j--]-'0';
carry = temp / 10; //进位
res += to_string(temp % 10); //余数==本位
}
reverse(res.begin(), res.end());
return res;
}
};
之前写过的基本解法:
基本写法
class Solution {
public:
string addStrings(string num1, string num2) {
int int_1[5101], int_2[5101], int_sum[5101], i, j, k=0, len=0, carry=0, temp=0, t=0;
string res="";
for(i=0;i<5101;i++)
{ int_1[i]=0;
int_2[i]=0;
int_sum[i]=0;
}
len = 5101;
if(num1=="0"&&num2=="0")
return "0";
for(i=num1.size()-1; i>=0; i--)
int_1[k++] = num1[i]-'0';
for(i=num2.size()-1; i>=0; i--)
int_2[t++] = num2[i]-'0';
for(i=0; i<len; i++)
{
temp = int_1[i] + int_2[i] + carry;
int_sum[i] = temp%10;
carry = temp/10;
}
for(i=len-1;; i--)
{
if(int_sum[i]!=0)
{
t = i;
break;
}
}
for(j=t; j>=0; j--)
res+=to_string(int_sum[j]);
return res;
}
};