LeetCode·43. Multiply Strings

題目:

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.

思路:

只想出來簡單解法,但是時效不好,在討論區有一種很讚的處理方法:
Easiest JAVA Solution with Graph Explanation

代碼:

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1 == "0" || num2 == "0")
            return "0";
        string res = "";
        vector<int> nums(num1.size()+num2.size(), 0);

        int ni, nj, m; 
        for(int i = 0; i < num1.size(); ++i){
            ni = num1[i] - '0';
            for(int j = 0; j < num2.size(); ++j){
                nj = num2[j] - '0';
                m = ni * nj;
                nums[i+j] += m/10;
                nums[i+j+1] += m%10;
            }
        }

        for(int i = nums.size()-1; i > 0; --i){
            if(nums[i] >= 10){
                nums[i-1] += nums[i] / 10;
                nums[i] = nums[i]%10;
            }
        }

        if(nums[0] == 0){
            for(int i = 1; i < nums.size(); ++i)
                res += to_string(nums[i]);
        }else{
            for(int i = 0; i < nums.size(); ++i)
                res += to_string(nums[i]);
        }

        return res;
    }
};

結果:


這裏寫圖片描述

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