Multiply Strings

来源:互联网 发布:python类型转换 编辑:程序博客网 时间:2024/06/06 02:02

一. 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
原创粉丝点击