[Leetcode] Multiply Strings

Multiply Strings Mar 12 '12 4253 / 16074

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

 

把num reverse一下,这个技巧挺实用,可以拓展到所有的string运算中。

 

class Solution {
public:
    string multiply(string num1, string num2) {

        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        
        int l1 = num1.size();
        int l2 = num2.size();
        string res(l1 + l2 + 1, '0');
        int carr = 0, t, idx;
        for (int i = 0; i < l1; ++i)
        {
            int n1 = num1[i] - '0';
            carr = 0;
            for (int j = 0; j < l2; ++j)
            {
                t = carr + n1 * (num2[j] - '0') + (res[i + j] - '0');
                carr = t / 10;
                res[i+j] = t % 10 + '0';
            }
            idx = l2;
            while (carr != 0)
            if (carr != 0) {
                t = carr + (res[i+idx] - '0');
                carr = t / 10;
                res[i+idx++] = t % 10 + '0';
            }
        }
        while (!res.empty() && res.back() == '0') res.pop_back();
        if (res.empty()) return "0";
        reverse(res.begin(), res.end());
        return res;
    }
};

 

你可能感兴趣的:(LeetCode)