Python活力练习Day20

Day20:给定两个字符串,求两数之和

  eg : inpur: num1 = "12",num2 = "23"

    output : 35

#不能直接将字符串转换成整数进行相加

 1 def add_num(num1,num2):
 2     res = "" #用来存储每位的数字
 3     i = len(num1) - 1 #num1的尾部
 4     j = len(num2) - 1 #num2的尾部
 5     carry = 0 #看是否产生进位,初始不进位,所以为0
 6     while i >= 0 or j >= 0:
 7         n1 = int(num1[i]) if i >= 0 else 0
 8         n2 = int(num2[j]) if j >= 0 else 0
 9         tmp = n1 + n2 + carry
10         carry = tmp // 10
11         res = str(tmp % 10) + res
12         i -= 1
13         j -= 1
14     return '1' + res if carry else res
15 
16 
17 num1 = '12'
18 num2 = '23'
19 print(add_num(num1,num2))

输出结果:35

另一种情形:给定一个列表和一个数字,求出他们的和

  eg : input : A = [9,9,9,9,9,9,9,9,9,9] ,K = 1

    output : 10000000000

 1 def addTOArrayForm(A,k):
 2     res = ""
 3     i = len(A) - 1
 4     j = len(str(k)) - 1
 5     carry = 0
 6     while i >= 0 or j >= 0:
 7         n1 = A[i] if i >= 0 else 0
 8         n2 = int(str(k)[j]) if j >= 0 else 0
 9         tmp = n1 + n2 + carry
10         carry = tmp // 10
11         res = str(tmp % 10) + res
12         i -= 1
13         j -= 1
14 
15     return '1' + res if carry else res
16 
17 A = [9,9,9,9,9,9,9,9,9,9]
18 K = 1
19 print(addTOArrayForm(A,K))

输出结果:

猜你喜欢

转载自www.cnblogs.com/xiaodangdang/p/12154714.html