The Add Strings solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Add Strings
C++, Python and TypeScript solutions for Add Strings.
Solution files
Python•add-strings/synced-solution.py
def addStrings(num1, num2):
result = []
carry = 0
i, j = len(num1) - 1, len(num2) - 1
while i >= 0 or j >= 0 or carry:
n1 = int(num1[i]) if i >= 0 else 0
n2 = int(num2[j]) if j >= 0 else 0
total = n1 + n2 + carry
result.append(str(total % 10))
carry = total // 10
i -= 1
j -= 1
return ''.join(reversed(result))
C++•add-strings/synced-solution.cpp
class Solution {
public:
string addStrings(string num1, string num2) {
string result = "";
int carry = 0;
int i = num1.length() - 1;
int j = num2.length() - 1;
while (i >= 0 || j >= 0 || carry) {
int n1 = i >= 0 ? num1[i] - '0' : 0;
int n2 = j >= 0 ? num2[j] - '0' : 0;
int total = n1 + n2 + carry;
result = char((total % 10) + '0') + result;
carry = total / 10;
i--;
j--;
}
return result;
}
};
TypeScript•add-strings/synced-solution.ts
function addStrings(num1: string, num2: string): string {
let result = "";
let carry = 0;
let i = num1.length - 1;
let j = num2.length - 1;
while (i >= 0 || j >= 0 || carry) {
const n1 = i >= 0 ? parseInt(num1[i]) : 0;
const n2 = j >= 0 ? parseInt(num2[j]) : 0;
const total = n1 + n2 + carry;
result = String(total % 10) + result;
carry = Math.floor(total / 10);
i--;
j--;
}
return result;
}