LeetCode 43. Multiply Strings

本文介绍了一种Python实现,提供Solution类的方法multiply,用于计算两个非负整数字符串的乘积,不借助于内置的BigInteger库,并通过str_add函数进行逐位相乘和进位处理。重点在于展示如何通过字符串操作实现复杂计算。
摘要由CSDN通过智能技术生成

题目描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

代码 (Python3)

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        ans = '0'
        cnt = 0
        for i in range(len(num1) - 1, -1, -1): 
            temp = '0'
            for j in range(int(num1[i])):
                temp = self.str_add(temp, num2)

            for i in range(cnt):
                temp += '0'
            print(temp, 123)
            cnt += 1

            ans = self.str_add(temp, ans)
        
        if ans.startswith('0'):
            return '0'
        return ans

    def str_add(self, s1, s2):  # 定义两个字符串的加法运算
        jw = 0
        if len(s2) > len(s1):
            s1, s2 = self.swap(s1, s2)
        s1 = list(s1)
        s2 = list(s2)
        i = len(s1) - 1
        j = len(s2) - 1
        while i >= 0 and j >= 0:
            now = int(s1[i]) + int(s2[j]) + jw
            jw = now // 10
            s1[i] = str(now % 10)
            i -= 1
            j -= 1

        if jw and len(s1) == len(s2):
            s1.insert(0, '1')
        elif jw:
            while i >= 0:
                now = int(s1[i]) + jw
                jw = now // 10
                s1[i] = str(now % 10)
                i -= 1
            if jw:
                s1.insert(0, '1')

        return "".join(s1)

    def swap(self, s1, s2):
        temp = s1
        s1 = s2
        s2 = temp
        return s1, s2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值