-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum of two large numbers.py
59 lines (45 loc) · 1.19 KB
/
sum of two large numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Python3 program to find sum of
# two large numbers.
# Function for finding sum of
# larger numbers
def findSum(str1, str2):
# Before proceeding further,
# make sure length of str2 is larger.
if (len(str1) > len(str2)):
t = str1;
str1 = str2;
str2 = t;
# Take an empty string for
# storing result
str = "";
# Calculate length of both string
n1 = len(str1);
n2 = len(str2);
# Reverse both of strings
str1 = str1[::-1];
str2 = str2[::-1];
carry = 0;
for i in range(n1):
# Do school mathematics, compute
# sum of current digits and carry
sum = ((ord(str1[i]) - 48) +
((ord(str2[i]) - 48) + carry));
str += chr(sum % 10 + 48);
# Calculate carry for next step
carry = int(sum / 10);
# Add remaining digits of larger number
for i in range(n1, n2):
sum = ((ord(str2[i]) - 48) + carry);
str += chr(sum % 10 + 48);
carry = (int)(sum / 10);
# Add remaining carry
if (carry):
str += chr(carry + 48);
# reverse resultant string
str = str[::-1];
return str;
# Driver code
str1 = "12";
str2 = "198111";
print(findSum(str1, str2));
# This code is contributed by mits