Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: e numbers can be arbitrarily large and are non-negative.
#include<iostream>
#include<string>
using namespace std;
string MultiplyString(string s1, string s2)//不考慮非法輸入了。。。
{
int punctindex1 = 0;
int punctindex2 = 0;
int index = 0;
for (string::iterator it = s1.begin(); it != s1.end(); ++it, index++)
{
if (*it == '.')
{
s1.erase(it);
punctindex1 = index;
break;
}
}
index = 0;
for (string::iterator it = s2.begin(); it != s2.end(); ++it, index++)
{
if (*it == '.')
{
s2.erase(it);
punctindex2 = index;
break;
}
}
int len1 = s1.size();
int len2 = s2.size();
int *p = new int[len1 + len2 + 1];
for (int i = 0; i <= len1 + len2; i++) p[i] = 0;
for (int j = len2-1; j >= 0; j--)
{
int tmp2 = s2[j] - '0';
for (int i = len1-1; i >= 0; i--)
{
int tmp1 = s1[i] - '0';
p[i + j + 2] += tmp1*tmp2;
}
}
for (int i = len1 + len2; i >= 1; i--)
{
int pre = p[i] / 10;
p[i] = p[i] % 10;
p[i - 1] += pre;
}
//===
string res;
for (int i = 0; i <= len1 + len2; i++)
{
char tmp = p[i] + '0';
res.push_back(tmp);
//處理小數點情況
if ((punctindex1 != 0 && punctindex2 != 0) && i == punctindex1 + punctindex2 )//都有小數點
res.push_back('.');
if ((punctindex1 != 0 && punctindex2 == 0) && i == punctindex1 + len2)//S1有小數點
res.push_back('.');
if ((punctindex1 == 0 && punctindex2 != 0) && i == len1 + punctindex2)//S2有小數點
res.push_back('.');
}
if (res.find('.') == string::npos)
{
bool flag = true;
string result;
for (int i = 0; i < res.size(); i++)
{
if (res[i] == '0'&&flag)
continue;
flag = false;
result.push_back(res[i]);
}
return result;
}
else
{
bool flag = true;
int nonzerosindex = 0;
for (int i = 0; i < res.size(); )
{
if (res[i] == '0')
i++;
else
{
nonzerosindex = i; break;
}
}
int punctindex = res.find('.');
if (nonzerosindex < punctindex)
return res.substr(nonzerosindex, res.size() - nonzerosindex);
else
return res.substr(punctindex - 1, res.size() - punctindex + 1);
}
}
int main()
{
string s1 = "10.0003";
string s2 = "36.00036";
string res = MultiplyString(s1, s2);
cout << res << endl;
}