【每日一題】43. Multiply Strings

題目描述

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

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示為字符串形式。

num1 和 num2 的長度小于110。
num1 和 num2 只包含數字 0-9。
num1 和 num2 均不以零開頭,除非是數字 0 本身。
不能使用任何標準庫的大數類型(比如 BigInteger)或直接將輸入轉換為整數來處理。

題解

由于題目要求:不能將字符串轉化成大整數來處理。所以需要換一種方法,這里打算模仿2個整數的計算過程,直接計算結果。

模仿自己手算整數的計算:把兩個數末尾對齊,固定一個數字a,從末尾開始,依次用數字與另個整數b的末尾開始相乘,計算進位數、余數;整數b遍歷完成后,將指向a中的數字向前移動一位,反復計算,直到數字a遍歷完成。

值得注意的是:需要先設定一個字符串用戶存儲臨時的結果。所以,我們要明確字符串的長度,設整數1、整數2長度分別為m,n;那么乘法結果的最大長度為m+n。兩個數字都遍歷完成后,對臨時結果從頭到尾進行遍歷,舍去其中為‘0’的字符。

完整代碼:

class Solution {
public:
    string multiply(string num1, string num2) {
        int size1 = num1.size(), size2 = num2.size();
        string res(size1+size2, '0');
        
        for (int i=size1-1; i>=0; --i){
            for (int j=size2-1; j>=0; --j){
                int temp = (num1[i] - '0') * (num2[j] - '0') + (res[i+j+1] - '0');
                res[i+j] += temp / 10 ;
                res[i+j+1] = temp % 10 + '0';
            }
        }
        
        for (int i=0; i< size1+size2; i++){
            if (res[i] != '0')
                return res.substr(i);
        }
        return "0";
    }
};

歡迎關注公眾號,一起學習
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。