Add Strings

easy math string simulation

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.

Inputnum1 = "456", num2 = "77"
Output"533"
Add digit by digit from the right, carrying when the sum exceeds 9.

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;
}
Time: O(max(m, n)) Space: O(max(m, n))