問題描述
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.
補(bǔ)充說明:
這個(gè)題目的要求是:給定你兩個(gè)字符串,然后需要把它們兩個(gè)相加,得到它的值,值同樣為字符串。但這里有個(gè)要求,就是不允許使用相關(guān)的庫將輸入轉(zhuǎn)換為integer(整數(shù))。
方案分析
- 這個(gè)題目就是典型的字符串轉(zhuǎn)換數(shù)字的方式,傳統(tǒng)的c或者java程序肯定想到的是
ascii碼的加減形式實(shí)現(xiàn)。 - 這里使用python,python的特性就是可以將字符串轉(zhuǎn)換為list,然后逐位相加,生成list,最后將這個(gè)list轉(zhuǎn)換為字符串即可。
python實(shí)現(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')
# 將兩個(gè)字符串逆序后,轉(zhuǎn)換為list,這里題目有要求,不能使用庫函數(shù)直接把string轉(zhuǎn)換為int,需要我們自己實(shí)現(xiàn)一個(gè)字符串轉(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 # 較短的那一位如果不夠,則該位補(bǔ)0
tmp = n + carry + num1[i] # 有進(jìn)位,則將進(jìn)位加上
num1[i] = tmp % 10
carry = tmp // 10
# 最后存在進(jìn)位,記得將這個(gè)進(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中的高級(jí)方法——izip_longest,這個(gè)函數(shù)能將兩個(gè)字符串轉(zhuǎn)換為每位對(duì)應(yīng)的tuple,不夠的可以補(bǔ)齊你指定的字符,這個(gè)方法簡(jiǎn)直太好用了。話不多說,貼出他人的代碼。
python實(shí)現(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