String Multiplication

Posted by simply on Sat, 05 Oct 2019 19:03:21 +0200

Title address

https://leetcode-cn.com/problems/multiply-strings/

Title Description: String Multiplication

Given two non-negative integers num1 and num2 in the form of strings, the product of num1 and num2 is returned, and their product is also expressed in the form of strings.

Example:

Example 1:

Input: num1 = 2, num2 = 3

Output: "6"

Example 2:

Input: num1 = 123, num2 = 456

Output: "56088"

Explain:

  1. The length of num1 and num2 is less than 110.
  2. num1 and num2 contain only numbers 0-9.
  3. Neither num1 nor num2 starts with zero, unless it's the number 0 itself.
  4. No large number type of standard libraries, such as BigInteger, can be used or input can be converted directly to integers.

Answer

A clumsy method is adopted: each bit in num1 is multiplied by num2, and the results are added up.

Code:

class Solution {
public:
    void update( int& CF, int& temp, string& res){
        if( temp >= 10)
            temp -= 10, CF = 1;
        else
            CF = 0;
        res += temp + '0';
    }
    //string add
    string add( string& num1, string& num2){
        if( num1.size() > num2.size())
            swap( num1, num2);  //num1.size() <= num2.size();
        
        string res;
        int CF = 0;

        for( int i = num1.size() - 1, j = num2.size() - 1; i > -1 && j > -1; i--, j--){
            int temp = num1[i] - '0' + num2[j] - '0' + CF;
            update( CF, temp, res);
        }
        
        for( int i = num2.size() - num1.size() - 1; i > -1; i--){
            int temp = num2[i] - '0' + CF;
            update( CF, temp, res);
        }
        
        if( CF == 1)
            res += '1', CF = 0;
        
        reverse( res.begin(), res.end());
        return res;
    }
    
    string mul( char& t, string& num, int count){
        int CF = 0;
        string res;
        
        for( int i = num.size() - 1; i >-1; i--){
            int temp = (num[i] - '0') * ( t - '0') + CF;
            if( temp >= 10)
                CF = temp / 10, temp %= 10;
            else
                CF = 0;
            res += temp + '0';
        }
        
        if( CF)
            res += CF + '0';
        
        reverse( res.begin(), res.end());
        
        while( count--)
            res += '0';
        
        return res;
    }
        
    string multiply(string num1, string num2) {
        if( num1 == "0" || num2 == "0")
            return "0";
        
        string res = "0";

        for( int i = num1.size() - 1, count = 0; i > -1; i--, count++){
            string temp = mul( num1[i], num2, count);
            res = add( res, temp);
        }
            
        return res;
    }
};

Topics: less