Add Strings
Problem
Given two non-negative integers num1 and num2 represented as strings, return their sum as a string. You may not convert the inputs to integers directly or use any built-in BigInteger.
num1 = "456", num2 = "77""533"def add_strings(a, b):
i, j, carry = len(a) - 1, len(b) - 1, 0
out = []
while i >= 0 or j >= 0 or carry:
x = ord(a[i]) - 48 if i >= 0 else 0
y = ord(b[j]) - 48 if j >= 0 else 0
s = x + y + carry
out.append(chr(s % 10 + 48))
carry = s // 10
i -= 1; j -= 1
return ''.join(reversed(out))
function addStrings(a, b) {
let i = a.length - 1, j = b.length - 1, carry = 0;
const out = [];
while (i >= 0 || j >= 0 || carry) {
const x = i >= 0 ? a.charCodeAt(i) - 48 : 0;
const y = j >= 0 ? b.charCodeAt(j) - 48 : 0;
const s = x + y + carry;
out.push(String.fromCharCode(s % 10 + 48));
carry = Math.floor(s / 10);
i--; j--;
}
return out.reverse().join('');
}
class Solution {
public String addStrings(String a, String b) {
int i = a.length() - 1, j = b.length() - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry > 0) {
int x = i >= 0 ? a.charAt(i) - '0' : 0;
int y = j >= 0 ? b.charAt(j) - '0' : 0;
int s = x + y + carry;
sb.append((char)(s % 10 + '0'));
carry = s / 10;
i--; j--;
}
return sb.reverse().toString();
}
}
string addStrings(string a, string b) {
int i = a.size() - 1, j = b.size() - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int x = i >= 0 ? a[i] - '0' : 0;
int y = j >= 0 ? b[j] - '0' : 0;
int s = x + y + carry;
out.push_back((char)(s % 10 + '0'));
carry = s / 10;
i--; j--;
}
reverse(out.begin(), out.end());
return out;
}
Explanation
Since we can't convert the strings to real numbers, we add them the way you would by hand on paper: digit by digit, starting from the rightmost end, carrying over whenever a column sums past 9.
Two pointers i and j start at the last digit of each number, and a carry starts at 0. Each step adds the two current digits plus the carry. We convert a character to its value with ord(ch) - 48 (subtracting the code of '0'), and if a pointer has run off the front we treat that digit as 0.
For a column sum s, the digit we keep is s % 10 and the new carry is s // 10. We append the digit and step both pointers left. The loop keeps going while either pointer is still valid or there is a leftover carry, which handles a final carried 1.
Example: num1 = "456", num2 = "77". Rightmost: 6+7 = 13 → write 3, carry 1. Next: 5+7+1 = 13 → write 3, carry 1. Next: 4+0+1 = 5 → write 5. Digits collected back-to-front are 3,3,5.
Because we build the answer from least-significant digit first, we reverse it at the end to get "533".