Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format. Please review my code. Is there a cleaner way of writing the code where we have to add the 2 doubles digit by digit?
for example, s1 is '9.9' and s2 is '8.8', we need to return '18.7'. The requirement is that we cannot pad zeros for cases like adding '9.9' and '7.899'. In another word, we cannot change the input into '9.900' (i.e: with padded 0's) and '7.899'.
we have to add the two input digit by digit. For example, if s1 = '9.9' and s2 = '7.899', then we need to do 8+9 (the digit after the decimal point in s1 and s2), 9+7 (the two digits before the decimal points in s1 and s2). In another words, please do not use internal libraries to convert the two numbers into float and add them together.
def addDoubles(s1, s2):
s1Split = s1.find('.')
s2Split = s2.find('.')
s1Post = ''
s2Post = ''
if s1Split != -1:
s1Post = s1[s1Split+1:]
if s2Split != -1:
s2Post = s2[s2Split+1:]
s1PostLen = len(s1Post)
s2PostLen = len(s2Post)
s1PostLonger = s2PostLonger = False
postLenDiff = 0
if s1PostLen > s2PostLen:
#s2Post = s2Post + '0'*(s1PostLen-s2PostLen)
s1PostLonger = True
postLenDiff = s1PostLen - s2PostLen
elif s1PostLen < s2PostLen:
#s1Post = s1Post + '0'*(s2PostLen-s1PostLen)
s2PostLonger = True
postLenDiff = s2PostLen - s1PostLen
if s1Split != -1:
s1New = s1[:s1Split] + s1Post
else:
s1New = s1
if s2Split != -1:
s2New = s2[:s2Split] + s2Post
else:
s2New = s2
postSum = helper(s1New, s2New, postLenDiff, s1PostLonger, s2PostLonger)
print('s2PostLonger =', s2PostLonger)
if s1PostLonger or (s1PostLonger == s2PostLonger == False and s1Post != ''):
postSum = postSum[:-s1PostLen] + '.' + postSum[-s1PostLen:]
elif s2PostLonger:
postSum = postSum[:-s2PostLen] + '.' + postSum[-s2PostLen:]
return postSum
def helper(one, two, postLenDiff, s1PostLonger, s2PostLonger):
oneIdx = len(one)-1
twoIdx = len(two)-1
curSum = 0
res = ''
if s1PostLonger:
res = one[-postLenDiff:]
oneIdx = oneIdx - postLenDiff
elif s2PostLonger:
res = two[-postLenDiff:]
twoIdx = twoIdx - postLenDiff
while oneIdx >= 0 or twoIdx >= 0 or curSum>0:
if oneIdx >= 0:
curSum += int(one[oneIdx])
oneIdx -= 1
if twoIdx >= 0:
curSum += int(two[twoIdx])
twoIdx -= 1
res = str(curSum%10) + res
curSum //= 10
return res