Skip to content

Instantly share code, notes, and snippets.

@prograsshopper
Created September 7, 2019 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prograsshopper/ddde6848b7037abef6df12382fabded5 to your computer and use it in GitHub Desktop.
Save prograsshopper/ddde6848b7037abef6df12382fabded5 to your computer and use it in GitHub Desktop.
command-line program that prints out the sum of two non-negative integers
# Write a command-line program that prints out the sum of two non-negative integers as input arguments.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
import sys
def get_sum(first_num, second_num):
first_list = [s for s in first_num]
second_list = [s for s in second_num]
end = 0
head = []
if len(first_list) > len(second_list):
end = len(second_list)
head = first_list[:len(first_list) - end]
elif len(first_list) < len(second_list):
end = len(first_list)
head = second_list[:len(second_list) - end]
else:
end = len(first_list)
sum_result = []
prev = 0
for i in range(1, end+1):
current_num = int(first_list[-i]) + int(second_list[-i])
if prev:
current_num += 1
if current_num >= 10:
prev = 1
current_num -= 10
else:
prev = 0
sum_result.insert(0, str(current_num))
result = "".join(sum_result)
if prev:
if not head:
result = "1" + result
else:
for i in range(1, len(head)+1):
target = int(head[-i]) + 1
if target >= 10:
head[-i] = str(target - 10)
else:
head[-i] = str(target)
prev = 0
if prev:
head.insert(0, str(1))
if head:
result = "".join(head) + result
print(result)
if __name__ == '__main__':
get_sum(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment