[LeetCode]43.Multiply Strings,multiplystrings

來源:互聯網
上載者:User

[LeetCode]43.Multiply Strings,multiplystrings
【題目】

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.

【分析】

高精度乘法(大數乘法)

其實更多地是考察乘法運算的本質。基本思路是和加法運算有一定的相似處,都是從低位到高位對每一位進行計算。只是進位和結果長度複雜一些。

我們仍然是從低位到高位對每一位進行計算,假設第一個數長度是n,第二個數長度是m,我們知道結果長度為m+n或者m+n-1(沒有進位的情況)。

對於最終結果上的某一位i,要計算這個位上的數字,我們需要對所有能組合出這一位結果的位進行乘法,即第1位和第i位,第2位和第i-1位,... ,然後累加起來,

最後我們取個位上的數值,然後剩下的作為進位放到下一輪迴圈中。在這裡我們每一組合時都要計算有沒有產生進位,如果有放到下一位上,不用所有累加起來在計算。

時間複雜度是O(m*n)  空間複雜度O(m+n)。

【代碼】

/**********************************   日期:2015-01-28*   作者:SJF0115*   題目: 43.Multiply Strings*   網址:https://oj.leetcode.com/problems/multiply-strings/*   結果:AC*   來源:LeetCode*   部落格:**********************************/#include <iostream>#include <cstring>using namespace std;class Solution {public:    string multiply(string num1, string num2) {        int len1 = num1.length();        int len2 = num2.length();        // 容錯處理        if(len1 <= 0 || len2 <= 0){            return "";        }//if        int sum = 0;        int len3 = len1 + len2;        char result[len3];        memset(result,'0',sizeof(result[0])*(len3+1));        for(int i = len1 - 1,m = 0;i >= 0;--i,++m){            for(int j = len2 - 1,n = 0;j >= 0;--j,++n){                sum = (num1[i] - '0') * (num2[j] - '0') + result[m+n] - '0';                result[m+n] = sum % 10 + '0';                // 進位                result[m+n+1] += sum / 10;            }//for        }//for        //確定乘積的位元        while(result[len3] == '0' && len3 > 0){            --len3;        }//while        //注意:加'\0'        result[len3+1] = '\0';        //翻轉        int temp;        for(int i = 0,j = len3;i < j;++i,--j){            temp = result[i];            result[i] = result[j];            result[j] = temp;        }//for        return string(result);    }};int main(){    Solution solution;    string num1("0");    string num2("123");    string result = solution.multiply(num1,num2);    // 輸出    cout<<result<<endl;    return 0;}/*for(int i = 0;i < result.size();++i){        for(int j = 0;j < result[i].size();++j){            cout<<result[i][j]<<" ";        }        cout<<endl;    }*/


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.