I'm trying to solve the following problem, which how to add two strings without converting them to integer. I have found a solution to the problem, but I don't understand it. Would someone explain it in plain english please ?
here is the code :
class Solution {
public:
string addStrings(string num1, string num2) {
int i=num1.size()-1,j=num2.size()-1,carry=0;
string res="";
while(i>=0||j>=0)
{
if(i>=0) carry+=num1[i--]-'0';
if(j>=0) carry+=num2[j--]-'0';
res=to_string(carry%10)+res;
carry/=10;
}
return carry?"1"+res:res;
}
};
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…