15.6—细节实现题—Multiply Strings

来源:互联网 发布:知乎 收入 安排 编辑:程序博客网 时间:2024/05/19 07:07
描述
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);elsereturn 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;}