414python
144git
Favorite数组
Share Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.bash
Note:app
The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.ui
思路:字符串转换为数组,遍历,经过unicode获取值,carry用来记录进位,arr记录每位的运算结果,最后arr用join链接起来spa
代码:python3code
class Solution(object):
def addStrings(self, num1, num2):
l1,l2=list(num1),list(num2)
carry=0
arr=[]
while l1 or l2:
a=ord(l1.pop())-ord('0') if len(l1)>0 else 0
b=ord(l2.pop())-ord('0') if len(l2)>0 else 0
c=a+b+carry
arr.append(str(c%10))
carry=int(c/10)
if carry>0:
arr.append(str(carry))
return ''.join(arr)[::-1]
复制代码