題目
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- 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.
難度
Easy
方法
從低位到高位相加列牺,每一位的結(jié)果為除10取余痰腮,如果有進位1,則在下一位求和的時候需要+1肝集,循環(huán)處理即可吊说。注意最高位相加后如果有進位,需要在結(jié)果的最前面補1
python代碼
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
i = len(num1) - 1
j = len(num2) - 1
num = ""
carry = 0
while i >= 0 or j >= 0:
result = carry
if i >= 0:
result += int(num1[i])
if j >= 0:
result += int(num2[j])
if result >= 10:
carry = 1
else:
carry = 0
num = str(result % 10) + num
i -= 1
j -= 1
if carry == 1:
num = "1" + num
return num
assert Solution().addStrings("111", "234965") == "235076"
assert Solution().addStrings("999", "1") == "1000"