Bigint Multiplication:大數乘法(hihoCoder C++)__C++

來源:互聯網
上載者:User
Bigint Multiplication

時間限制:10000ms
單點時限:1000ms
記憶體限制:256MB 描述

Given 2 nonnegative integers a and b, calculate a × b. 輸入

One line with 2 integers a and b separated by a single space.

0 ≤ a, b ≤ 10100. 輸出

The value of a × b. 範例輸入

100000000000000000000 100000000000000000000 範例輸出

10000000000000000000000000000000000000000 題目解讀

類比豎式乘法,其中一個逐位乘以另一個數,再將結果乘以十的對應次冪累加起來。

思路:
1. 大數加大數,這個很好實現。
2. 大數乘個位元,這個也很好實現。
3. 大數乘大數,可以變成大數分別乘個位元,然後用大數加大數進行匯總。

另外需要注意有0的情況。

#include <iostream>#include <string>#include <algorithm>using namespace std;// char to intinline int c2i(char c){    return c - '0';}// int to charinline char i2c(int i){    return i + '0';}// string(one number) multiply char(one bit of the other number)string sMc(string s, char c) {    reverse(s.begin(), s.end());    string r;    int carry = 0;    for (int i = 0; i < s.length(); ++i) {        int n = c2i(s[i]) * c2i(c) + carry;        r += i2c(n % 10);        carry = n / 10;    }    if (carry != 0) {        r += i2c(carry);    }    reverse(r.begin(), r.end());    return r;}// string(one number) add string(the other number)string sAs(string s1, string s2) {    if (s1.length() < s2.length()) {        swap(s1, s2);    }    s2 = string(s1.length() - s2.length(), '0').append(s2);    reverse(s1.begin(), s1.end());    reverse(s2.begin(), s2.end());    string s3;    int carry = 0;    for (int i = 0; i < s1.length(); ++i) {        int n = c2i(s1[i]) + c2i(s2[i]) + carry;        s3 += i2c(n % 10);        carry = n / 10;    }    if (carry != 0) {        s3 += i2c(carry);    }    reverse(s3.begin(), s3.end());    return s3;}// string(one number) multiply string(the other number)string sMs(string s1, string s2) {    if (s1 == "0" || s2 == "0") {        return "0";    }    if (s1.length() < s2.length()) {        swap(s1, s2);    }    string s3;    for (int i = 0; i < s2.length(); ++i){        string t = sMc(s1, s2[s2.length() - 1 - i]);        s3 = sAs(s3, t + string(i, '0'));    }    return s3;}int main(){    string s1, s2, s3;    cin >> s1 >> s2;    s3 = sMs(s1, s2);    cout << s3 << 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.