Skip to main content

415. 字符串相加 [easy]

415. 字符串相加 [easy]

https://leetcode-cn.com/problems/add-strings/

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

  • num1 和num2 的长度都小于 5100.
  • num1 和num2 都只包含数字 0-9.
  • num1 和num2 都不包含任何前导零。
  • 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

通过次数46,224 | 提交次数91,144

Second Try

2020-08-03

还是补零大法好,方便快捷

class Solution:
@staticmethod
def atoi(a):
return ord(a) - ord('0')

@staticmethod
def itoa(i):
return chr(i + ord('0'))

def addStrings(self, num1: str, num2: str) -> str:
if len(num1) < len(num2):
num1 = "0" * (len(num2) - len(num1)) + num1
elif len(num1) > len(num2):
num2 = "0" * (len(num1) - len(num2)) + num2

rv = ""
carry = 0
for i in reversed(range(len(num1))): # reversed容易遗漏
carry, res = divmod(self.atoi(num1[i]) + self.atoi(num2[i]) + carry, 10)
rv = self.itoa(res) + rv
if carry:
rv = self.itoa(carry) + rv
return rv
  • 执行用时:76 ms, 在所有 Python3 提交中击败了14.66%的用户
  • 内存消耗:13.6 MB, 在所有 Python3 提交中击败了89.58%的用户

First Try

2020-08-03

做过好几次类似的了,这次不用补零,而是当长度不足的时候用0替代。

n是从0开始迭代,但是获取num的时候需要从末尾开始,num1[len(num1] - 1 - i]这部分比较容易出错,不如一开始直接reversed;其次是最后额外的carry部分比较容易遗漏。

不能用数字字符直接转换,只能用ord和chr两个内置unicode函数了。

In [1]: ord?
Signature: ord(c, /)
Docstring: Return the Unicode code point for a one-character string.
Type: builtin_function_or_method

In [2]: chr?
Signature: chr(i, /)
Docstring: Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
Type: builtin_function_or_method

class Solution:
@staticmethod
def atoi(a):
return ord(a) - ord('0')

@staticmethod
def itoa(i):
return chr(i + ord('0'))

def addStrings(self, num1: str, num2: str) -> str:

n = max(len(num1), len(num2))
carry = 0
rv = ""
for i in range(n):
lft = self.atoi(num1[len(num1) - 1 - i]) if i < len(num1) else 0
rt = self.atoi(num2[len(num2) - 1 - i]) if i < len(num2) else 0
carry, res = divmod((lft + rt + carry), 10)
rv = self.itoa(res) + rv
if carry:
rv = self.itoa(carry) + rv
return rv
  • 执行用时:64 ms, 在所有 Python3 提交中击败了35.36%的用户
  • 内存消耗:13.7 MB, 在所有 Python3 提交中击败了61.81%