LeetCode 415. Add Strings: CPP Solution
Problem Statement
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
The value of each number is < 5100.
Num1 and num2 only contain 0-9 as digits.
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.
Function Signature (C++):
string addStrings(string num1, string num2)
Inputs:
num1 = "5"
num2 = "193"
Outputs:
"198"
TL;DR Code Solution
string addStrings(string num1, string num2) {
string result;
int indexOne = num1.length() - 1;
int indexTwo = num2.length() - 1;
int carry = 0;
while (indexOne >= 0 || indexTwo >= 0 || carry) {
int current = carry;
if (indexOne >= 0) {
current += num1[indexOne] - '0';
}
if (indexTwo >= 0) {
current += num2[indexTwo] - '0';
}
carry = current / 10;
current = current % 10;
result = (char)(current + '0') + result;
indexOne--;
indexTwo--;
}
return result;
}