File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/python3
2
+ """
3
+ Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
4
+
5
+ Note:
6
+ The length of both num1 and num2 is < 5100.
7
+ Both num1 and num2 contains only digits 0-9.
8
+ Both num1 and num2 does not contain any leading zero.
9
+ You must not use any built-in BigInteger library or convert the inputs to integer directly.
10
+ """
11
+
12
+
13
+ class Solution :
14
+ def int (self , n ):
15
+ return ord (n ) - ord ("0" )
16
+
17
+ def addStrings (self , num1 , num2 ):
18
+ """
19
+ :type num1: str
20
+ :type num2: str
21
+ :rtype: str
22
+ """
23
+ ret = []
24
+ # let num2 to be one has more digit
25
+ if len (num1 ) > len (num2 ):
26
+ num1 , num2 = num2 , num1
27
+
28
+ num1 = num1 [::- 1 ]
29
+ num2 = num2 [::- 1 ]
30
+ carry = 0
31
+ idx = 0
32
+ while idx < len (num2 ):
33
+ if idx < len (num1 ):
34
+ s = self .int (num1 [idx ]) + self .int (num2 [idx ]) + carry
35
+ else :
36
+ s = self .int (num2 [idx ]) + carry
37
+
38
+ if s >= 10 :
39
+ s -= 10
40
+ carry = 1
41
+ else :
42
+ carry = 0
43
+
44
+ ret .append (s )
45
+ idx += 1
46
+
47
+ if carry :
48
+ ret .append (carry )
49
+
50
+ return "" .join (map (str , ret [::- 1 ]))
51
+
52
+
53
+ if __name__ == "__main__" :
54
+ assert Solution ().addStrings ("9999" , "1" ) == "10000"
55
+ assert Solution ().addStrings ("9999" , "9999" ) == "19998"
56
+ assert Solution ().addStrings ("23" , "8" ) == "31"
You can’t perform that action at this time.
0 commit comments