Monday, June 1, 2020

Adding two positive floating point numbers as strings


Interview Question

Q: Assume there are 2 numbers like 2.39 and 0.9 in string format "2.39" and "0.9". Without using any standard string-to-numeric conversion library functions, try to sum the two numbers and represent the output also as a string. Both numbers are assumed to be always positive.

n1 = "12.39"
n2 = "9.999"

(a, b) = n1.split('.')
(c, d) = n2.split('.')

l1 = abs(len(a) - len(c))
if len(a) > len(c):
    c = ''.join(['0'] * l1) + c  # 0000...
else:
    a = ''.join(['0'] * l1) + a

l1 = abs(len(b) - len(d))
if len(b) > len(d):
    d = d + ''.join(['0'] * l1)
else:
    b = b + ''.join(['0'] * l1)

M = '0'+ a + "." + b # Overflow of carry possible - padding with leading zero
N = '0'+ c + "." + d # Overflow of carry possible - padding with leading zero

print("->", M, N)

OUTPUT = []
carry = 0
for i in range(len(M) - 1, -1, -1):
    if M[i] == '.':
        OUTPUT.append('.')
        continue
    else:
        tmp = carry + (ord(M[i]) - 48) + (ord(N[i]) - 48)
        carry = tmp // 10
        OUTPUT.append(str(tmp % 10))

OUTPUT = OUTPUT[::-1]  # reverse the list
if OUTPUT[0] == '0':
    OUTPUT.pop(0)
print(OUTPUT[0])
OUTPUT = ''.join(OUTPUT)
print (OUTPUT)