Big Integer Addition
Python
Hard
4 views
Problem Description
Two non-negative integers a and b are provided as strings (very large). Output a+b.
Input Format
Two lines: a then b.
Output Format
One line sum.
Sample Test Case
Input:
999999999999999999
1
Output:
1000000000000000000
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
a=lines[0].strip()
b=lines[1].strip()
i=len(a)-1
j=len(b)-1
carry=0
out=[]
while i>=0 or j>=0 or carry:
s=carry
if i>=0:
s+=ord(a[i])-48
i-=1
if j>=0:
s+=ord(b[j])-48
j-=1
out.append(chr(48+(s%10)))
carry=s//10
out.reverse()
sys.stdout.write(''.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!