问题:https://leetcode.com/problems/add-strings/?tab=Description
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.给定两个字符串形式的正整数num1和num2,计算num1和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.
在不用库的情况下实现加法。
分析:注意进位,注意处理长短不一样的数字,从末尾开始相加。如果两个字符长度都小于等于0,返回空字符串。某一个长度小于0,返回另一个字符串即可。对于数字和字符的相互转换,这里需要用到‘0’。字符转数字,减去’0’。数字转字符,加上’0’。
C++代码:
class Solution {
public:
string addStrings(string num1, string num2) {
int l1=num1.size();
int l2=num2.size();
if(l1<=0 && l2<=0){
return " " ;
}
else if(l1<=0){
return num2;
}
else if(l2<=0){
return num1;
}
else{
string res="";
int m=min(l1,l2);
int i=l1-1;
int j=l2-1;
int a=0;
int sum=0;
while(m>0){
sum=a+(num1[i]-'0')+(num2[j]-'0');
a=sum/10;
res+=sum%10+'0';
i--;
j--;
m--;
}
while(i!=-1){
sum=a+(num1[i]-'0');
a=sum/10;
res+=sum%10+'0';
i--;
}
while(j!=-1){
sum=a+(num2[j]-'0');
a=sum/10;
res+=sum%10+'0';
j--;
}
if(i==-1 && j==-1 && a!=0){
res+=a+'0';
}
reverse(res.begin(), res.end());
return res;
}
}
};