[Leetcode]Multiply Strings

本文详细介绍了如何使用字符串操作实现大数乘法算法,包括数位反转、逐位相乘、进位处理及结果整理等关键步骤。

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.

大数乘法~依旧是从低位到高位进行运算,可以先把num1, num2反转以方便进行运算~注意最后要去掉结果数组中高位的0,并且对结果数组进行反转~

class Solution:
    # @param num1, a string
    # @param num2, a string
    # @return a string
    def multiply(self, num1, num2):
        if num1 is None or num2 is None or len(num1) == 0 or len(num2) == 0:
            return ""
        if num1[0] == '0' or num2[0] == '0': return '0'
        num1 = [ord(i) - ord('0') for i in num1][::-1]
        num2 = [ord(i) - ord('0') for i in num2][::-1]
        total = [0] * (len(num1) + len(num2))
        for i in xrange(len(num1)):
            for j in xrange(len(num2)):
                total[i + j] += num1[i] * num2[j]
        carry, res = 0, []
        for sum in total:
            sum += carry
            carry = sum / 10
            res.append(str(sum % 10))
        while len(res) > 1 and res[-1] == '0':
            res.pop()
        return ''.join(res[::-1])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值