Leetcode127: Multiply Strings

来源:互联网 发布:评价网络调查的方法 编辑:程序博客网 时间:2024/06/07 18:21

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) {        if(num1 == "0" || num2 == "0")            return "0";        int l1 = num1.size();        int l2 = num2.size();        int* n1 = new int[l1];        int* n2 = new int[l2];        int* n3 = new int[l1+l2];        memset(n3, 0, sizeof(int)*(l1+l2));        for(int i = 0; i < l1; i++)        {            n1[i] = num1[i]-'0';        }        for(int i = 0; i < l2; i++)        {            n2[i] = num2[i]-'0';        }        for(int i = 0; i < l1; i++)        {            for(int j = 0; j < l2; j++)            {                n3[i+j+1] += n1[i]*n2[j];            }        }        string s;        for(int i = l1+l2-1; i >= 0; i--)        {            if(i>0)            {                n3[i-1] += n3[i]/10;            }            n3[i] %= 10;            s = char(n3[i]+'0')+s;        }        if(s[0]=='0')            s = s.substr(1);        return s;    }};


0 0