Skip to content

Commit d34e289

Browse files
committed
415
1 parent a944043 commit d34e289

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

415 Add Strings.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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"

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy