multiply string

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1.empty() || num2.empty() || num1 == "0" || num2 == "0")
        {
            return "0";
        }

        string rst;

        for(int i = num2.length()-1; i >= 0; i--)
        {
            int carry = 0;
            string temp;
            for(int r = 0; r < num2.length() - i - 1; r++)
            {
                temp.push_back('0');    
            }

            for(int j = num1.length()-1; j >= 0; j--)
            {
                int cur = stoi(num2.substr(i, 1)) * stoi(num1.substr(j, 1)) + carry;
                temp.append(to_string(cur%10));
                carry = cur/10;
            }

            if(carry != 0)
            {
                temp.append(to_string(carry));
            }

            reverse(temp.begin(), temp.end());
            rst = add(rst, temp);
        }

        return rst;
    }

    string add(string num1, string num2)
    {
        string rst;

        int i = num1.length()-1;
        int j = num2.length()-1;
        int carry = 0;

        while(i >= 0 && j >= 0)
        {
            int cur = stoi(num1.substr(i, 1)) + stoi(num2.substr(j, 1)) + carry;
            rst.append(to_string(cur%10));
            carry = cur/10;
            i--;
            j--;
        }

        while(i >= 0)
        {
            int cur = stoi(num1.substr(i, 1)) + carry;
            rst.append(to_string(cur%10));
            carry = cur/10;
            i--;
        }

        while(j >= 0)
        {
            int cur = stoi(num2.substr(j, 1)) + carry;
            rst.append(to_string(cur%10));
            carry = cur/10;
            j--;
        }

        if(carry != 0)
        {
            rst.append(to_string(carry));
        }

        reverse(rst.begin(), rst.end());

        return rst;

    }
};

results matching ""

    No results matching ""