Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
思路:直观思路,就是模拟乘法过程。注意进位。我写的比较繁琐。
string multiply(string num1, string num2) { vector<int> v1, v2, vmulti; vector<vector<int>> vvtmp; int l1 = num1.size(); int l2 = num2.size(); if(l1 == 1 && num1[0] == '0') return "0"; if(l2 == 1 && num2[0] == '0') return "0"; int maxl = 0; //用vector存储两个数字 v[0]是最高位 for(int i = 0; i < l1; i++) v1.push_back(num1[i] - '0'); for(int i = 0; i < l2; i++) v2.push_back(num2[i] - '0'); //乘步骤 for(int i = l1 - 1; i >= 0; i--) { vector<int> vtmp; //v[0]是最低位 int t = i; while(t < l1 - 1) //后面补错位的0 { vtmp.push_back(0); t++; } int c = 0; //记录进位 for(int j = l2 - 1; j >= 0; j--) { int cur = v1[i] * v2[j] + c; vtmp.push_back(cur % 10); c = cur / 10; } if(c != 0) vtmp.push_back(c); vvtmp.push_back(vtmp); maxl = (vtmp.size() > maxl) ? vtmp.size() : maxl; } //加步骤 int c = 0; //记录进位 for(int i = 0; i < maxl; i++) { int cur = c; for(int j = 0; j < vvtmp.size(); j++) { if(i >= vvtmp[j].size()) continue; cur += vvtmp[j][i]; } vmulti.push_back(cur % 10); c = cur / 10; } if(c != 0) vmulti.push_back(c); //转换为string string ans; for(int i = vmulti.size() - 1; i >= 0; i--) { ans += (vmulti[i] + '0'); } return ans; }
大神总是能把多个步骤一次到位:
string multiply(string num1, string num2) { string sum(num1.size() + num2.size(), '0'); for (int i = num1.size() - 1; 0 <= i; --i) { int carry = 0; for (int j = num2.size() - 1; 0 <= j; --j) { int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; //把当前乘出来的数字和之前的数字以及进位相加 sum[i + j + 1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry; //这个是最高位多出来的进位 其他的都是i+j+1 这里没有+1 } size_t startpos = sum.find_first_not_of("0"); if (string::npos != startpos) { return sum.substr(startpos); } return "0"; }