43. Multiply Strings

本文介绍了一种处理任意大小整数相乘的算法实现,采用标准的手动乘法策略,通过双层循环从输入数字的末尾开始计算。文章提供了一个C++类解决方案,详细展示了如何避免使用内置的大数库,如BigInteger,并且不将输入字符串转换为整数。

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

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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

解答:

This is the standard manual multiplication algorithm. We use two nested for loops, working backward from the end of each input number. We pre-allocate our result and accumulate our partial result in there. One special case to note is when our carry requires us to write to our sum string outside of our for loop.

At the end, we trim any leading zeros, or return 0 if we computed nothing but zeros.

用num1.size()+num2.size()的长度作为结果,这里多了一位是怕高位有进制

同时注意从不是0的数字开始,若全是0则返回字符串0


class Solution {
public:
    string multiply(string num1, string num2) {
        string sum(num1.size()+num2.size(),'0');
        for(int i = num1.size()-1; i >= 0; i--){
            int carry = 0;
            for(int j = num2.size()-1; j >= 0; j--){
                int temp = (sum[i + j + 1] - '0') + (num1[i] - '0')*(num2[j] - '0') + carry;
                sum[i + j + 1] = temp % 10 + '0';
                carry = temp / 10;
            }
            sum[i] += carry;
        }
        size_t t = sum.find_first_not_of("0");
        if(t != string::npos)
        return sum.substr(t);
        else
        return "0";
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值