Leetcode 43. Multiply Strings (python+cpp)

博客介绍了LeetCode 43题——Multiply Strings的解法,包括两种思路,一种利用当前数字位置计算乘积,另一种在二刷时提出更直观的逻辑方法,避免了整数与字符转换的过程。还提到了相关字符串运算的补充阅读材料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

在这里插入图片描述

解法:

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == '0' or num2 == '0':
            return '0'
        # initialize the product as a list, the length of the product of these two num won't exceed the sum of length of num1 and num2
        product = [0] * (len(num1) + len(num2))
        # initialize the operation position, starting from the end of the product list
        pos = len(product) - 1
        for n1 in reversed(num1):
            # store the position for multiplying a single char in num1 with the entire num2
            curr_pos = pos
            for n2 in reversed(num2):
                # add the results at corresponding position
                product[curr_pos] += (ord(n1) - ord('0')) * (ord(n2) - ord('0'))
                # take care of the carry
                product[curr_pos - 1] += product[curr_pos] // 10
                product[curr_pos] %= 10
                curr_pos -= 1
            pos -= 1
        ans = ''
        # removed the starting 0s
        i = 0
        while i < len(product):
            if product[i] != 0:
                break
            i += 1
        while i < len(product):
            ans = ans + str(product[i])
            i += 1
        return ans

解法2: 利用两个数字的当前位置找到乘积的正确位置

class Solution:
    def multiply(self, num1: str, num2: str) -> str:    
        if num1 == '0' or num2 == '0':
            return '0'
        product = [0] * (len(num1) + len(num2))
        for i in range(len(num1)-1,-1,-1):
            for j in range(len(num2)-1,-1,-1):
                # compute multiplication of current two position
                res = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
                # use i,j to find the correct position and take care of the carry
                product[i + j + 1] += res
                product[i + j] += product[i + j + 1] // 10
                product[i + j + 1] %= 10
                  
        ans = ''
        while i < len(product):
            if product[i] != 0:
                break
            i += 1
            
        while i < len(product):
            ans = ans + str(product[i])
            i += 1
        
        return ans

follow up:关于string的加减乘看这两篇:链接1 链接2

二刷

二刷写了一种更加符合逻辑的方法,跟我们人计算乘积比较一致,而且没有参杂整数和字符之间的相互转换。上面两种解法最后还是加了证书到字符的转换的

class Solution {
public:
    string singleMul(string num1,char d){
        string ans = "";
        int carry = 0;
        for(int i=num1.size()-1;i>=0;i--){
            auto c = num1[i];
            int res = (c-'0') * (d-'0') + carry;
            // cout << res << endl;
            carry = res / 10;
            ans = char((res%10) + '0') + ans;
        }
        if(carry) ans = char((carry+'0')) + ans;
        return ans;
    }
    string add(string num1,string num2){
        string ans = "";
        int carry = 0;
        int p1 = num1.size()-1;
        int p2 = num2.size()-1;
        
        while(p1 >= 0 || p2 >= 0){
            // cout << p1 << p2 << endl;
            int v1 = p1 >= 0 ? num1[p1] - '0' : 0;
            int v2 = p2 >= 0 ? num2[p2] - '0' : 0;
            
            ans = char((v1 + v2 + carry) % 10 + '0') + ans;
            // cout << ans << endl;
            carry = (v1 + v2 + carry) / 10;
            p1--;
            p2--;
        }
        if(carry) ans = char((carry+'0')) + ans;
        return ans;
    }
    string multiply(string num1, string num2) {
        // cout << singleMul("123",'5') << endl;
        if(num1 == "0" || num2 == "0") return "0";
        if(num2.size() == 1) return singleMul(num1,num2[0]);
        string ans = "0";
        for(int i = num2.size()-1;i>=0;i--){
            string tmp = singleMul(num1,num2[i]);
            for(int j=1;j<num2.size()-i;j++){
                tmp += "0";
            }
            // cout << tmp << endl;
            ans = add(ans,tmp);
            // cout << ans << endl;
        }
        return ans;
        // return "";
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值