Multiply Strings

一. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Difficulty:Medium

TIME:TIMEOUT

解法

這道題其實就是高精度乘法,說實話之前一直都是用高精度加法配合實現的,因爲如果按照人類本身的思維方式來計算,確實要用到高精度加法。

但其實這道題正確的做法並不需要高精度加法,而是通過每兩個數相乘累加就可以了。

這裏寫圖片描述

我們可以把兩個數相乘的值映射到結果字符串中的兩個位置上,這樣不斷累加就得到了結果。

string multiply(string num1, string num2) {
    int len1 = num1.size();
    int len2 = num2.size();
    string result(len1 + len2,'0'); //初始化結果字符串(注意長度一定是len1+len2)
    for(int i = len1 - 1; i >= 0; i--) {
        for(int j = len2 - 1; j >= 0; j--) {
            //計算兩個數相乘,相乘的結果一定是一個兩位數,注意這裏要加上結果字符串中對應的個位數
            int value = (num1[i] - '0') * (num2[j] - '0') + result[i + j + 1] - '0';
            //這裏直接加上進位(注意這裏加上進位之後可能值會大於9,但是沒有影響,在後面的計算中,這個值終歸會小於10)
            result[i + j] += value / 10;
            //重新對個位數賦值(這個操作會讓十位數的值終歸會降到10以下)
            result[i + j + 1] = value % 10 + '0';
        }
    }
    int i = 0;
    //刪除前導0
    while(i < result.size() && result[i] == '0')
        i++;
    if(i != result.size())
        return result.substr(i);
    return "0";
}

代碼的時間複雜度爲O(n2)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章