GeorgeDI

BigNumbers

Jan 12th, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. def add_arrays(arr1, arr2):
  2. # make sure arr1 is the shorter array
  3. if len(arr1) > len(arr2):
  4. arr1, arr2 = arr2, arr1
  5.  
  6. # add the arrays element-wise
  7. result = []
  8. carry = 0
  9. for i in range(len(arr1)):
  10. res = arr1[i] + arr2[i] + carry
  11. result.append(res % 10)
  12. carry = res // 10
  13.  
  14. # add the remaining elements of arr2, if any
  15. for i in range(len(arr1), len(arr2)):
  16. res = arr2[i] + carry
  17. result.append(res % 10)
  18. carry = res // 10
  19.  
  20. # add the carry, if any
  21. if carry > 0:
  22. result.append(carry)
  23.  
  24. return result
  25.  
  26.  
  27. # read size of arrays
  28. size = input().strip().split()
  29.  
  30. # read the first array
  31. arr1 = input().strip().split()
  32. arr1 = [int(x) for x in arr1]
  33.  
  34. # read the second array
  35. arr2 = input().strip().split()
  36. arr2 = [int(x) for x in arr2]
  37.  
  38. # add the arrays and print the result
  39. result = add_arrays(arr1, arr2)
  40. print(" ".join(str(x) for x in result))
Advertisement
Add Comment
Please, Sign In to add comment