415. Add Strings

作者 汪小祯 日期 2017-02-01
415. Add Strings

题目

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.

思路

按位依次加上去
比如 1234 567这两个数
先算 4+7 结果是11,那么保留个位1,把十位1用carry存下来 ———>1
然后继续3+6+carry 结果是10 同理保留0,1存下来到xiayiwei ——->0
2+5+1 ——->8
1 ——–>1
得到1081,然后把数组反过来就是1801,最终结果

题解

class Solution {
public:
string addStrings(string num1, string num2) {
int i=num1.size()-1;
int j=num2.size()-1;
string res="";
int carry=0;
for (int k=0;i>=0||j>=0||carry;i--,j-- ) {
int num=0;
if(i>=0) num+=(num1[i]-'0');
if(j>=0) num+=(num2[j]-'0');
num+=carry;
carry=num/10;
num=num%10;
res+=to_string(num);
}
reverse(res.begin(),res.end());
return res;
}
};