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

相關文章
相關標籤/搜索