問題描述
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.
補充說明:
這個題目的要求是:給定你兩個字符串,然后需要把它們兩個相加庄萎,得到它的值踪少,值同樣為字符串。但這里有個要求糠涛,就是不允許使用相關(guān)的庫將輸入轉(zhuǎn)換為integer(整數(shù))援奢。
方案分析
- 這個題目就是典型的字符串轉(zhuǎn)換數(shù)字的方式,傳統(tǒng)的c或者java程序肯定想到的是
ascii
碼的加減形式實現(xiàn)忍捡。 - 這里使用python集漾,python的特性就是可以將字符串轉(zhuǎn)換為list,然后逐位相加砸脊,生成list具篇,最后將這個list轉(zhuǎn)換為字符串即可。
python實現(xiàn)
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
def _convertInter(num):
return ord(num) - ord('0')
# 將兩個字符串逆序后凌埂,轉(zhuǎn)換為list驱显,這里題目有要求,不能使用庫函數(shù)直接把string轉(zhuǎn)換為int瞳抓,需要我們自己實現(xiàn)一個字符串轉(zhuǎn)換數(shù)字的函數(shù)秒紧。
num1, num2 = list(map(_convertInter, num1[::-1])), list(map(int, num2[::-1]))
# 如果num2的長度 大于 num1,交換它們的順序挨下。
if len(num1)<len(num2):
num1, num2 = num2, num1
carry = 0
for i in range(len(num1)):
n = num2[i] if i<len(num2) else 0 # 較短的那一位如果不夠熔恢,則該位補0
tmp = n + carry + num1[i] # 有進(jìn)位,則將進(jìn)位加上
num1[i] = tmp % 10
carry = tmp // 10
# 最后存在進(jìn)位臭笆,記得將這個進(jìn)位加上叙淌。
if carry:
num1.append(1)
# 這里沒有要求不能將integer轉(zhuǎn)換為str,所以直接使用了內(nèi)建函數(shù)str()
return ''.join(map(str, num1))[::-1]
方案分析2
- 在leetcode社區(qū)愁铺,看到有人使用了
itertools
中的高級方法——izip_longest
鹰霍,這個函數(shù)能將兩個字符串轉(zhuǎn)換為每位對應(yīng)的tuple,不夠的可以補齊你指定的字符茵乱,這個方法簡直太好用了茂洒。話不多說,貼出他人的代碼瓶竭。
python實現(xiàn)2
from itertools import izip_longest
class Solution(object):
def addStrings(self, num1, num2):
res, c = "", 0
for (x, y) in izip_longest(num1[::-1], num2[::-1], fillvalue='0'):
s = (int(x) + int(y) + c)
d, c = s % 10, int(s / 10)
res = str(d) + res
if c > 0: res = str(c) + res
return res