https://oj.leetcode.com/problems/multiply-strings/
用字符串实现大数乘法,细节题,细节很多
class Solution { public: string multiply(string num1, string num2) { if(num1.empty() || num1.size() == 0 || num2.empty() || num2.size() == 0) return ""; //0 if(num1 == "0" || num2 == "0") return "0"; //keep num2 the smaller if(num1.size() < num2.size()) { //exchange string t = num1; num1 = num2; num2 = t; } string ans = ""; ans.resize(num1.size()); //initialize for(size_t i = 0; i < num1.size(); i++) ans[i] = '0'; int pos = 0; int times = 0; int sum = 0; for(int index2 = num2.size() - 1; index2 >= 0; index2--) { pos = ans.size() - 1 - times; times++; int carry = 0; for(int index1 = num1.size() - 1; index1 >=0; index1--) { sum = carry + (num1[index1] - '0')*(num2[index2] - '0') + ans[pos] - '0'; carry = sum/10; ans[pos] = sum%10 + '0'; pos--; // ans has been the beginning while index1 not, and ans has been the beginning and here are carry if(pos == -1 &&(carry > 0|| index1 != 0)) { string t = "0"; t[0] = carry + '0'; ans = t + ans; carry = 0; pos = 0; } } } return ans; } };