the problem I am solving is to find the sum of two large numbers, where the numbers are given as strings. the algorithm is :
- Reverse both strings.
- Keep adding digits one by one from 0’th index (in reversed strings) to end of smaller string, append the sum % 10 to end of result and keep track of carry as sum / 10.
- Finally reverse the result.
This was the code I tried:
def stringadd(s1, s2):
s1 = s1[::-1]
s2 = s2[::-1]
m = len(s1)
n = len(s2)
carry = 0
s = ""
if len(s1) > len(s2):
temp = s2
s2 = s1
s1 = temp
for i in range(m):
su, = (ord(s1[i]) - 48) + (ord(s2[i]) - 48) + carry
s += chr(sum % 10 + 48)
carry = int(sum / 10)
for i in range(m, n):
sum = (ord(s2[i]) - 48) + carry
s += chr(sum % 10 + 48)
carry = int(sum / 10)
i += 1
if carry:
s += chr(carry + 48)
s = s[::-1]
return s
print(stringadd("32134", "23456782"))
I am getting a string index out of range error in the line 17 which is
sum = (ord(s1[i]) - 48) + (ord(s2[i]) - 48) + carry