美文网首页
LeetCode 反转字符串中的单词

LeetCode 反转字符串中的单词

作者: FlyCharles | 来源:发表于2019-03-03 20:39 被阅读0次
class Solution(object):
    def multiply(self, num1, num2):
        num1 = num1[::-1]
        num2 = num2[::-1]
        length1 = len(num1)
        length2 = len(num2)
        temp = [0] * (length1 + length2)
        for i in range(length1):
            for j in range(length2):  
                temp[i+j] += int(num1[i]) * int(num2[j])
    
        result = []
        for i, num in enumerate(temp):
            digit = num % 10
            carry = num / 10 
            result.insert(0, str(digit))
            if i < length1 + length2 - 1:
                temp[i+1] += carry
        while result[0] == '0' and len(result) > 1: # "9133" * "0"
            result.pop(0)   
        return "".join(result)

测试

if __name__ == "__main__":
    s = Solution()
    inputs  = [["982","125"], ["12345","567"], ["12345","0"], ["0","0"], ["0","567"]]
    outputs = ["122750", "6999615", "0", "0", "0"]
    for i in range(len(inputs)):
        print s.multiply(inputs[i][0], inputs[i][1]) == outputs[i]
True
True
True
True
True

相关文章

网友评论

      本文标题:LeetCode 反转字符串中的单词

      本文链接:https://www.haomeiwen.com/subject/awimuqtx.html