43. 字串相乘 - 8月13日
阿新 • • 發佈:2020-08-13
題目
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) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。