问题描述:
给定两个字符串形式的非负整数 num1
和num2
,计算它们的和。
注意:
num1
和num2
的长度都小于 5100.num1
和num2
都只包含数字0-9
.num1
和num2
都不包含任何前导零。- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
方法:
1 class Solution(object): 2 def addStrings(self, num1, num2): 3 """ 4 :type num1: str 5 :type num2: str 6 :rtype: str 7 """ 8 res = "" 9 c = 0 10 i , j = len(num1) -1,len(num2) - 1 11 while i >= 0 or j >= 0: 12 if i >= 0: 13 c += ord(num1[i]) - ord('0') 14 i -= 1 15 if j >= 0: 16 c += ord(num2[j]) - ord('0') 17 j -= 1 18 res = str(c % 10) + res 19 c //= 10 20 if c: 21 res = str(c) + res 22 return res
2018-10-01 09:04:24