Thursday, May 6, 2021

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.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0itself.

class Solution {
public:
    string multiply(string num1, string num2) {
        string ans = "";
        if (num1.size() == 0 || num2.size() == 0) {
            return "0";
        }
        if (num1 == "0" || num2 == "0") {
            return "0";
        }
        
        int it2 = num2.size() - 1;
        int count = 0;
        while(it2 >= 0) {
            string prod = product(num1, num2[it2]);
            for (int i = 0; i < count; i++) {
                prod.push_back('0');
            }
            ans = add(ans, prod);
            count++;
            it2--;
        }
        return ans;
    }
    
    string add(string num1, string num2) {
        if (num1 == "") {
            return num2;
        } else if (num2 == "") {
            return num1;
        }
        int it1 = num1.size() - 1;
        int it2 = num2.size() - 1;
        int carry = 0;
        string ans;
        while (it1 >= 0 || it2 >= 0) {
            int dig1 = (it1 >= 0 ? num1[it1] - '0' : 0);
            int dig2 = (it2 >= 0 ? num2[it2] - '0' : 0);
            int new_dig = (dig1 + dig2 + carry) % 10;
            carry = (dig1 + dig2 + carry) / 10;
            ans = to_string(new_dig) + ans;
            it1--;
            it2--;
        }
        if (carry != 0) {
            ans = to_string(carry) + ans;
        }
        return ans;
    }
    
    string product(string num1, char ch) {
        string ans;
        if (ch == '0' || num1 == "0") {
            return "0";
        }
        int it = num1.size() - 1;
        int carry = 0;
        while (it >= 0) {
            int dig = num1[it] - '0';
            int new_dig = dig * (ch - '0');
            ans = to_string((new_dig + carry) % 10) + ans;
            carry = (new_dig + carry) / 10;
            it--;
        }
        if (carry != 0) {
            ans = to_string(carry) + ans;
        }
        return ans;
    }
};


======== Smaller one ====

https://zxi.mytechroad.com/blog/string/leetcode-43-multiply-strings/


No comments:

Post a Comment