A 13ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        string multiply(string num1, string num2) {
            int len1 = num1.size(), len2 = num2.size();
            vector<int> line, ans;
            string ret = "";
            int carry = 0, mul1 = 0, mul2 = 0, temp;
            int m, n;
            int shift, check = 0;
            for(int i = len1 - 1; i >= 0 ; i--) {
                for(int j = len2 - 1; j >= 0; j--) {
                    mul1 = num1[i] - '0';
                    mul2 = num2[j] - '0';
                    if(i == len1 - 1) {
                        line.push_back((mul1*mul2 + carry)%10);
                        carry = (mul1*mul2 + carry)/10;
                    } else {
                        shift = (len1 - 1 - i) + (len2 - 1 - j);
                        if(shift < line.size()) {
                            temp = line[shift] + mul1*mul2 + carry;
                            line[shift] = temp%10;
                            carry = temp/10;
                        } else {
                            temp = mul1*mul2 + carry;
                            line.push_back(temp%10);
                            carry = temp/10;
                        }
                    }
                }
                if(carry) {
                    line.push_back(carry);
                    carry = 0;
                }
            }
            
            for(int ii = line.size() - 1; ii >= 0; ii--) {
                ret = ret + (char)(line[ii] + 48);
                check += line[ii];
            }
            return (check == 0)?"0":ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.