[leetcode] 43. Multiply Strings(大数相乘)

Multiply Strings

描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
1. The length of both num1 and num2 is < 110.
2. Both num1 and num2contains only digits 0-9.
3. Both num1 and num2 does not contain any leading zero.
4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

我的代码

大数相乘:看代码中注意点

class Solution {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        if (len1 == 0 || len2 == 0)  return "0";
        int *rlt = new int[(len1 + len2)];  //乘积的位数为len1+len2或者len1+len2-1
        memset(rlt, 0, (len1 + len2)*sizeof(int));
        for (int i = 0; i < len1; i++)
        {
            for (int j = 0; j < len2; j++)
            {
                rlt[i + j + 1] += (num1[i] - '0')*(num2[j] - '0');
                //之所以加个1是为了把首位空出来放进位
            }
        }
        for (int i = len1+len2-1; i >=1; i--)
        {
            if (rlt[i] >= 10) //进位
            {
                rlt[i - 1] += (rlt[i] / 10);
                rlt[i] = rlt[i] % 10;
            }
        }
        int ind = 0;
        while ((rlt[ind] == 0) && ind < len1+len2-1) ind++; //去掉开头的0,要考虑结果为0的情况,不能输出如“0000”而要输出“0”
        string sRlt="";
        for (; ind < len1 + len2; ind++)
        {
            sRlt += (rlt[ind] + '0');
        }
        delete[] rlt;
        return sRlt;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值