Add Strings
String Math
Problem
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Thought Process
This is very similar to Add Binary
Have to remember that we can have potentailly have carry so we need a variable for this
Solution
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
i = len(num1)-1
j = len(num2)-1
carry = 0
res = ""
while i>=0 or j >= 0:
numSum = carry
if i >= 0:
numSum+=ord(num1[i]) - ord('0')
if j >= 0:
numSum+=ord(num2[j]) - ord('0')
carry = 1 if numSum > 9 else 0
res+=str(numSum%10)
i-=1
j-=1
if carry != 0:
res+=str(carry)
return res[::-1]
Key Points
We have to remember there can potenially be a carry variable if the sum of two digits is greater than 9
Time Complexity
Time:
Space:
Last updated
Was this helpful?