C++ Solution


  • 0
    Y
    class Solution {
    public:
        string multiply(string num1, string num2) {
            const std::size_t n1(num1.size()), n2(num2.size());
            string reval(n1 + n2, '0');
            
            for (std::size_t i = n1; i-- > 0; ) {
                for (std::size_t j = n2; j-- > 0; ) {
                    std::size_t pos = i + j + 1;
                    std::size_t pre_pos = i + j;
                    int val = (reval[pos] - '0') + (num1[i] - '0') * (num2[j] - '0');
                    reval[pos] = '0' + (val % 10);
                    reval[pre_pos] += (val / 10); // May be larger than 10 at first, 
                                                  // but will be updated afterwards
                }
            }
            
            std::size_t non_zero = reval.find_first_not_of('0');
            if (non_zero == std::string::npos) return "0";
            else return reval.substr(non_zero);
        }
    };
    

Log in to reply
 

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