LeetCode:Multiply Strings

题目连接html

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算法

大整数乘法post


咱们以289*785为例ui

image

 

首先咱们把每一位相乘,获得一个没有进位的临时结果,如图中中间的一行红色数字就是临时结果,而后把临时结果从低位起依次进位。对于一个m位整数乘以n位整数的结果,最多只有m+n位。         本文地址.net

注意:结果中须要去掉前导0,还须要注意结果为0的状况code

class Solution {
public:
    string multiply(string num1, string num2) {
        int n1 = num1.size(), n2 = num2.size();
        vector<int> tmpres(n1+n2, 0);
        int k = n1 + n2 - 2;
        for(int i = 0; i < n1; i++)
            for(int j = 0; j < n2; j++)
                tmpres[k-i-j] += (num1[i]-'0')*(num2[j]-'0');
        int carryBit = 0;
        for(int i = 0; i < n1+n2; i++)//处理进位
        {
            tmpres[i] += carryBit;
            carryBit = tmpres[i] / 10;
            tmpres[i] %= 10;
        }
        int i = k+1;
        while(tmpres[i] == 0)i--;//去掉乘积的前导0
        if(i < 0)return "0"; //注意乘积为0的特殊状况
        string res;
        for(; i >= 0; i--)
            res.push_back(tmpres[i] + '0');
        return res;
    }
};

 

上述算法的复杂度为O(n^2)(假设整数长度为n)htm

另外更高效的计算大整数乘法通常有:(1)karatsuba算法,复杂度为3nlog3≈3n1.585,能够参考百度百科面试题——大整数乘法乘法算法-Karatsuba算法。(2)基于FFT(快速傅里叶变换)的算法,复杂度为o(nlogn), 能够参考FFT, 卷积, 多项式乘法, 大整数乘法blog

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3735309.htmlip

相关文章
相关标签/搜索