1 class Solution:
 2     def addToArrayForm(self, A, K):
 3         i = len(A) - 1
 4         while i >= 0 and K > 0:
 5             A[i] += K
 6             K = A[i] // 10
 7             if A[i] >= 10:
 8                 A[i] %= 10
 9                 if i == 0:
10                     A = [0] + A
11                     i += 1
12             i -= 1
13         return A
14         

 上面这个是参考别人的解决方案,思路不好理解,我又从新写了一个啰嗦的:

 1 class Solution:
 2     def addToArrayForm(self, A: 'List[int]', K: 'int') -> 'List[int]':
 3         lenA = len(A)
 4         KS = str(K)
 5         lenB = len(KS)
 6         B = list()
 7         maxlen = 0
 8         if lenA > lenB:
 9             maxlen = lenA
10             dis = lenA - lenB
11             for i in range(dis):
12                 B.append(0)
13         elif lenA < lenB:
14             maxlen = lenB
15             dis = lenB - lenA
16             for i in range(dis):
17                 A.insert(0,0)
18         else:
19             maxlen = lenA
20             
21         for i in range(lenB):
22             B.append(int(KS[i]))
23 
24         I = 0
25         R = list()
26         maxpotion = maxlen - 1
27         while maxpotion >= 0:
28             C = A[maxpotion] + B[maxpotion] + I
29             if C >= 10:
30                 I = 1
31                 C = C % 10
32             else:
33                 I = 0
34             R.insert(0,C)
35             maxpotion -= 1
36 
37         if I == 1:
38             R.insert(0,1)
39         return R

 

posted on 2019-02-10 13:59  Sempron2800+  阅读(157)  评论(0编辑  收藏  举报