Thursday, April 30, 2015

[LeetCode] Multiply Strings

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.
class Solution {
public:
    string multiply(string num1, string num2) 
    {
        string res(num1.size()+num2.size(), '0');
        for (int i=num1.size()-1;i>=0;i--) 
        {
            int overflow = 0;
            for (int j=num2.size()-1;j>=0;j--) 
            {
                int sum = res[i+j+1]-'0' + (num1[i]-'0')*(num2[j]-'0') + overflow;
                res[i + j + 1] = sum%10 + '0';
                overflow = sum/10;
            }
            res[i] += overflow;
        }
    
        size_t t = res.find_first_not_of("0");
        if (string::npos == t) return "0";
        return res.substr(t);
    }
    
};