这是四道笔试题的第二题:
两个字符串形式的数字,求相乘结果并保存到字符串,结果可能会很长,所以只能用字符串模拟乘法操作。
1、c+++代码如下:
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string multiply(string num1, string num2) {
int l = num1.length();
int r = num2.length();
vector<int> num(l+r,0);
for(int i=0;i<l;i++)
{
int n1=num1[l-1-i]-'0';
int tmp=0;
for(int j=0;j<r;j++)
{
int n2=num2[r-1-j]-'0';
tmp=tmp+num[i+j]+n1*n2;
num[i+j]=tmp%10;
tmp/=10;
}
num[i+r]=tmp;
}
int k=l+r-1;
while(k>0&&num[k]==0)k--;
string result="";
while(k>=0)result+=static_cast<char>('0'+num[k--]);
return result;
}
int main(){
string org;
getline(cin,org);
istringstream iss(org);
string a;
string b;
iss>> a >> b;
cout<<multiply(a,b)<<endl;
return 0;
参考的链接:
http://www.cnblogs.com/xinyuyuanm/archive/2013/04/26/3045598.html
牛客上的牛人解答:
https://www.nowcoder.com/discuss/30697?type=0&order=0&pos=17&page=2
https://www.nowcoder.com/discuss/30693?type=0&order=0&pos=25&page=1