Multiply Strings

一. Multiply Strings

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

Note:

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Difficulty:Medium

TIME:TIMEOUT

解法

这道题其实就是高精度乘法,说实话之前一直都是用高精度加法配合实现的,因为如果按照人类本身的思维方式来计算,确实要用到高精度加法。

但其实这道题正确的做法并不需要高精度加法,而是通过每两个数相乘累加就可以了。

这里写图片描述

我们可以把两个数相乘的值映射到结果字符串中的两个位置上,这样不断累加就得到了结果。

string multiply(string num1, string num2) {
    int len1 = num1.size();
    int len2 = num2.size();
    string result(len1 + len2,'0'); //初始化结果字符串(注意长度一定是len1+len2)
    for(int i = len1 - 1; i >= 0; i--) {
        for(int j = len2 - 1; j >= 0; j--) {
            //计算两个数相乘,相乘的结果一定是一个两位数,注意这里要加上结果字符串中对应的个位数
            int value = (num1[i] - '0') * (num2[j] - '0') + result[i + j + 1] - '0';
            //这里直接加上进位(注意这里加上进位之后可能值会大于9,但是没有影响,在后面的计算中,这个值终归会小于10)
            result[i + j] += value / 10;
            //重新对个位数赋值(这个操作会让十位数的值终归会降到10以下)
            result[i + j + 1] = value % 10 + '0';
        }
    }
    int i = 0;
    //删除前导0
    while(i < result.size() && result[i] == '0')
        i++;
    if(i != result.size())
        return result.substr(i);
    return "0";
}

代码的时间复杂度为 O(n2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值