Coder's Cat

LeetCode: Add Strings

2020-07-30

Solution for LeetCode challenge: 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.

Solution

Use the variable of carry to record whether we have a carry flag from previous iteration.

class Solution {
public:
string addStrings(string num1, string num2) {
string ans = "";
int carry = 0;
int l1 = num1.size() - 1;
int l2 = num2.size() - 1;
while(l1 >= 0 || l2 >= 0 || carry) {
int n1 = l1 >= 0 ? num1[l1] - '0' : 0;
int n2 = l2 >= 0 ? num2[l2] - '0' : 0;
int s = n1 + n2 + carry;
char v = '0' + (s % 10);
carry = (s >= 10) ? 1 : 0;
ans = v + ans;
l1--;
l2--;
}
return ans;
}
};