LeetCode 43. Multiply Strings

"""
大数相乘

1.开空间 
2.逆序
3.对位相乘
4.处理进位
5.处理前导0
6.逆序转化为答案

"""
class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num1 == "0" or num2 == "0":
            return "0"
        
        
        num1_len = len(num1)
        num2_len = len(num2)
        res = [0 for i in xrange( (num1_len + 1) * (num2_len + 1) )]
        
        num1 = num1[::-1]
        num2 = num2[::-1]
        
        #3.对位相乘
        for i in xrange(num1_len):
            num1_int = int(num1[i])
            for j in xrange(num2_len):
                num2_int = int(num2[j])
                res[i + j] += num1_int * num2_int
        #print res 
                
        #4.处理进位
        jinwei = 0
        for i in xrange(len(res)):
            temp_num = res[i] + jinwei
            if temp_num >= 10:
                jinwei = temp_num / 10
                temp_num = temp_num % 10
                res[i] = temp_num
            else:
                jinwei = 0
                res[i] = temp_num
                
        
        #5.处理前导0
        index = len(res) - 1
        while index >= 0:
            if res[index] != 0:
                break
            index -= 1
            
        res = res[:index+1]

        
        #6.转化为答案
        ans = ""
        index = len(res) - 1
        while index >= 0:
            ans += str(res[index])
            index -= 1
        return ans
        

                
                
                
                
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值