Multiply Strings 大数相乘

来源:互联网 发布:单例模式 java enum 编辑:程序博客网 时间:2024/05/29 07:12

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) {        if(num1=="0"||num2=="0")            return "0";        int i,j,len1,len2;        len1=num1.size();        len2=num2.size();        int *res=new int[len1+len2];        memset(res,0,sizeof(int)*(len1+len2));        for(i=0;i<len1;i++)        {            for(j=0;j<len2;j++)            {                res[i+j+1]+=(num1[i]-'0')*(num2[j]-'0');//res[0]空出来最高位进位            }        }                string str="";        for(i=len1+len2-1;i>=0;i--)        {            if(res[i]>=10)                res[i-1]+=res[i]/10;            res[i]%=10;            str=char(res[i]+'0')+str;        }        if(str[0]=='0')            str=str.substr(1);        return str;    }};

0 0