Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路

题目的思想非常简单,利用数学上的求余方法先把字符串对应位的数码转换成整数,再逐位相加即可。

有几个Python的知识点在注释当中指出,可以注意一下。在Python中使用List的开销还是相对较小的。

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
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
len1 = len(num1)
len2 = len(num2)
result = []
total = len1 if len1 > len2 else len2
carry = 0
for i in range(1,total+1):
if (i <= len1 and i <= len2):
#ord可以将char转换成ascii码
num = (ord(num1[-i]) - ord("0")) + (ord(num2[-i]) - ord("0")) + carry
else:
if (len1 > len2):
num = (ord(num1[-i]) - ord("0")) + carry
else:
num = (ord(num2[-i]) - ord("0")) + carry
if (num > 9):
num = num - 10
carry = 1
else:
carry = 0
result.append(num)
if (i == total):
if(carry):
result.append(carry)
result.reverse()
#这个是python里面list转string的方法,要牢记
#如果list里面的元素不是integer,用 res = ''.join(result)即可
res = ''.join(str(e) for e in result)
return res