题目
43. 字符串相乘
我的思路
我的思路是用num1的每一位去乘num2,产生num1长度个字符串,再把k个字符串相加。
我的实现
class Solution { public: string multiply(string num1, string num2) { int l1 = num1.size(); int l2 = num2.size(); vector<string> products; for(int i=l1-1;i>=0;i--){ string temp = ""; for(int num0 = 1;num0<l1-i;num0++){ temp += '0'; } int o = 0; int pro = 0; int n = 0; for(int j=l2-1;j>=0;j--){ pro = (num1[i] - '0')*(num2[j] - '0'); n = (pro+o)%10; o = (pro+o)/10; temp += (n+'0'); //cout<<"check"<<l2<<endl; } if(o>0) temp+= (o+'0'); //reverse(temp.begin(),temp.end()); products.push_back(temp); //cout<<temp<<endl; } //把得到的字符串相加 string result = ""; int preSum = 0; int nowSum = 0; for(int i=0;i<l1+l2;i++){ int k=0; //preSum = 0; nowSum = 0; for(int k =0;k<l1;k++){ if(i<products[k].size()){ nowSum += products[k][i] - '0'; } } nowSum = nowSum + preSum; //if(nowSum>0||i==0) result += '0' + nowSum%10; preSum = nowSum/10; //cout<<preSum<<endl; } while(preSum>0){ result += '0' + preSum%10; preSum = preSum/10; } int i = result.size()-1; while(*(result.end()-1)=='0'&&(result.end()-1)!=result.begin())result.erase(result.end()-1); //for() reverse(result.begin(),result.end()); return result; } }; /* 数字过长,无法用普通数据类型表示。 用num1的每一位去乘num2,产生x1个字符串,再把k个字符串相加。 */
拓展学习
官方题解的思路更优雅
class Solution { public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") { return "0"; } int m = num1.size(), n = num2.size(); auto ansArr = vector<int>(m + n); for (int i = m - 1; i >= 0; i--) { int x = num1.at(i) - '0'; for (int j = n - 1; j >= 0; j--) { int y = num2.at(j) - '0'; ansArr[i + j + 1] += x * y; } } for (int i = m + n - 1; i > 0; i--) { ansArr[i - 1] += ansArr[i] / 10; ansArr[i] %= 10; } int index = ansArr[0] == 0 ? 1 : 0; string ans; while (index < m + n) { ans.push_back(ansArr[index]); index++; } for (auto &c: ans) { c += '0'; } return ans; } }; 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/multiply-strings/solution/zi-fu-chuan-xiang-cheng-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。