415. Add Strings

Poby’s Home
Aug 10, 2021

easy

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

Solution

class Solution {
public:
string addStrings(string num1, string num2) {
int carry = 0;
int i = num1.size() - 1;
int j = num2.size() - 1;
string result;
while (i >= 0 || j >= 0 || carry) {
int temp = carry;
if (i>=0) {
temp += num1[i] - '0';
i--;
}
if (j>=0) {
temp += num2[j] - '0';
j--;
}
result = to_string(temp % 10) + result;
carry = temp / 10;
}
return result;
}
};

--

--