Problem Statement
(Source)Given two non-negative numbers 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.
Solution
第一遍从后往前扫描的时候先把中间结果(按位求和)存到较长的“数字”里,此时不考虑进位。第二遍从后往前扫描的时候处理进位。时间复杂度与空间复杂度均为: O(max(len(num1),len(num2))) .
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
x = map(int, list(num1))
y = map(int, list(num2))
if len(x) > len(y):
x, y = y, x
n1, n2 = len(x), len(y)
i, j = n1 - 1, n2 - 1
while i >= 0:
y[j] += x[i]
i -= 1
j -= 1
j = n2 - 1
while j >= 1:
if y[j] >= 10:
y[j - 1] += 1
y[j] -= 10
j -= 1
return ''.join(map(str, y))