leetcode43. Multiply Strings

本文介绍了一个使用C++实现的字符串乘法算法。该算法通过逐位相乘并累加的方式处理两个输入字符串,能够有效处理大数乘法问题。文章包含三个主要函数:multiply用于两字符串相乘、multiplyChar用于字符与字符串相乘、add用于两字符串相加。

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

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1.size()<=0 || num2.size()<=0) return "0";
        int maxPos =  num2.size() - 1;
        string product="0";
        string tempProduct = "";
        int zerosLen = 0;
        for(int i = maxPos ; i>=0 ; i--){
            zerosLen = maxPos - i;
            tempProduct = multiplyChar(num1,num2[i]);
            if(tempProduct!="0"){
                    tempProduct += string(zerosLen,'0');

                    product = add(product,tempProduct);
             }
        }
        return product;
    }
    string multiplyChar(string num1,char num2){
        if(num1.size()<=0 || num2 == '0' || num1=="0") return "0";
        int tempInt  =num2 - '0';
        string temp ="";
        int carry = 0;
        for(int i = num1.size() - 1;i>=0;i--){
            temp = string(1,(((num1[i] - '0') * tempInt  + carry)% 10) +'0') + temp;

            carry = ((num1[i] - '0') * tempInt  + carry) / 10 ;
        }
        if(carry>0) temp = string(1,carry+'0')+temp;
        return temp;
    }

    string add(string num1, string num2){
        if(num1.size()<=0 || num2.size()<=0) return num1+num2; 
        if(num1 == "0") return num2;
        if(num2 == "0") return num1;

        int cursor1 = num1.size() - 1;
        int cursor2 = num2.size() - 1;
        int carry = 0;
        string temp="";
        while(cursor1>=0 || cursor2>=0){
            int toAdd1 = cursor1>=0 ? num1[cursor1] - '0' : 0;
            int toAdd2 = cursor2>=0 ? num2[cursor2] - '0' : 0;
            temp = string(1,(( toAdd1+ toAdd2  + carry) % 10) +'0') + temp;
            carry = ( toAdd1+ toAdd2  + carry) / 10;

            cursor1>=0 && (cursor1--);
            cursor2>=0 && (cursor2--);
        }
        if(carry>0) temp = '1'+temp;

        return temp;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值