码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[43]Multiply Strings

时间:2015-02-10 14:38:57      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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

 

leetcode[43]Multiply Strings

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!