實現兩個字串的乘法

來源:互聯網
上載者:User

實現兩個由數字構成的字串的乘法,其實現代碼如下所示:

#include<iostream>#include<string>#include<vector>using namespace std;string multiply(string &num1, string &num2){if (num1 == "0" || num2 == "0"){return "0";}int len1 = num1.length();int len2 = num2.length();vector<int> result(len1 + len2 - 1, 0);string resultStr = "";for (int i = len1 - 1; i >= 0; --i){for (int j = len2 - 1; j >= 0; --j){result[i + j] += (num1[i] - '0')*(num2[j] - '0');//關鍵的一步,兩個位元和相等的乘積放在同一個地方}}string temp1, temp2;int k = len1 + len2 - 2;while (k != 0){temp1 = result[k] % 10 + '0';resultStr = temp1 + resultStr;result[k - 1] += result[k] / 10;--k;}temp1 = result[0] % 10 + '0';resultStr = temp1 + resultStr;if (result[0] >= 10){temp2 = result[0] / 10 + '0';resultStr = temp2 + resultStr;}return resultStr;}int main(){string s1 = "9";string s2 = "9";string s3 = "12564875421475";string s4 = "4578124754157841541";cout << "s1*s2 = " << multiply(s1, s2) << endl;cout << "s3*s4 = " << multiply(s3, s4) << endl;system("pause");return 0;}

實驗結果如下所示:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.