Problem
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Algorithm
Simulate calculation using arrays.
Code
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
i, j = len(num1) - 1, len(num2) - 1
remainder = 0
result = ""
while i >= 0 or j >= 0 or remainder:
n1 = ord(num1[i]) - ord('0') if i >= 0 else 0
n2 = ord(num2[j]) - ord('0') if j >= 0 else 0
bits = n1 + n2 + remainder
remainder = bits // 10
result = str(bits % 10) + result
i -= 1
j -= 1
return result