您的位置:首页 > 其它

leetcode: 43. Multiply Strings

2017-11-14 09:18 405 查看

Problem

# Given two numbers represented as strings, return multiplication of the numbers as a string.
#
# Note: The numbers can be arbitrarily large and are non-negative.


AC

最粗暴的方法莫过于此了:

class Solution():
def multiply(self, x1, x2):
return str(int(x1) * int(x2))


然而这显然不是面试官想考察的。。。

另一种比较“正经”的解法:

class Solution():
def multiply(self, x1, x2):
x1, x2, res = x1[::-1], x2[::-1], [0]*(len(x1) + len(x2))
for i in range(len(x1)):
for j in range(len(x2)):
res[i + j] += int(x1[i]) * int(x2[j])
res[i + j + 1] += res[i + j] // 10
res[i + j] %= 10
i = len(res) - 1
while i > 0 and res[i] == 0:
i -= 1
return ''.join(map(str, res[i::-1]))

if __name__ == "__main__":
assert Solution().multiply("123", "1000") == '123000'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: