题目:
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.
思路:大数相乘 使用字符串表示
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
/*
大数相乘 大数使用字符串表示 同时不用考虑负数
*/
/*
思路:对于结果页使用字符串表示,两个数相乘的结果长度不可能比两个数长度的和还要长
*/
int multiply(char a,char b)
{
int first = a-'0';
int second = b -'0';
return first*second;
}
string MultiplyStrings(string& first,string& second)
{
int len1 = first.length();
int len2 = second.length();
string result(len1+len2,'0');
int i,j;
int carry=0;
int tmp,tmp1,pos;
for(i=len2-1;i>=0;i--)
{
carry =0;
for(j=len1-1;j>=0;j--)
{
pos = len1-1+len2-1-i-j;
tmp = multiply(first[j],second[i]);
tmp1= (tmp%10 + carry+result[pos]-'0');
result[pos] = (char)(tmp1%10 +'0');
cout<<"pos is "<<pos<<" tmp is "<<tmp<<" tmp1 is "<<tmp1<<" i+j is "<<result[pos]<<endl;
carry = tmp/10+tmp1/10;
}
}
result.assign(result.begin(),result.begin()+pos+1);
reverse(result.begin(),result.end());
return result;
}
int main()
{
string first("12345678");
string second("12345678");
string result = MultiplyStrings(first,second);
cout<<result<<endl;
return 0;
}