您的位置:首页 > 其它

Leetcode Multiply Strings

2014-06-06 19:37 246 查看
题目链接:https://oj.leetcode.com/problems/multiply-strings/


Multiply Strings

Total Accepted: 8084 Total
Submissions: 40447My Submissions

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.

Have you been asked this question in an interview?

模拟大整数乘法,用经典的算法即可解决问题。

class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0"||num2=="0") return "0";
int l1=num1.size(),l2=num2.size();
int *n1=new int [l1],*n2=new int [l2],*res=new int [l1+l2];
memset(res,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++)
res[i+j+1]+=n1[i]*n2[j];
string ans="";
for(int k=l1+l2-1;k>=0;k--){
if(k>0) res[k-1]+=res[k]/10;
res[k]%=10;
ans=char(res[k]+'0')+ans;
}
ans=ans[0]=='0'?ans.substr(1):ans;
delete []n1;
delete []n2;
delete []res;
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: