高精度乘法

普通竖式相乘

image.png
记得要补0。

  1. class Solution {
  2. public:
  3. string multiply(string num1, string num2) {
  4. int m = num1.length(), n = num2.length();
  5. // 忘记了考虑0的情况,wa了一次
  6. if(num1[0]=='0'||num2[0]=='0') return "0";
  7. vector<int> A,B,M,C;
  8. for(int i=m-1;i>=0;i--) A.push_back(num1[i]-'0');
  9. for(int i=n-1;i>=0;i--) B.push_back(num2[i]-'0');
  10. string s;
  11. if(m>n) s = num2, M = A;
  12. else s = num1, M = B;
  13. for(int i=s.length()-1;i>=0;i--){
  14. vector<int> tmp = mul(M,s[i]-'0');
  15. int diff = s.length()-1-i;
  16. while(diff){
  17. auto it = tmp.begin();
  18. tmp.insert(it,0);
  19. diff--;
  20. }
  21. if(i==s.length()-1) C = tmp;
  22. else C = add(C,tmp);
  23. }
  24. string res = "";
  25. for(int i = C.size()-1;i>=0;i--){
  26. res += C[i]+'0';
  27. }
  28. return res;
  29. }
  30. vector<int> mul(vector<int>A,int num){
  31. int v = 0;
  32. vector<int> res;
  33. for(int i=0;i<A.size();i++){
  34. v += A[i]*num;
  35. res.push_back(v%10);
  36. v = v/10;
  37. }
  38. if(v) res.push_back(v);
  39. return res;
  40. }
  41. vector<int> add(vector<int>A,vector<int>B){
  42. if(A.size()<B.size()) return add(B,A);
  43. vector<int> C;
  44. int v = 0;
  45. for(int i=0;i<A.size();i++){
  46. v += A[i];
  47. if(i<B.size()) v+= B[i];
  48. C.push_back(v%10);
  49. v /= 10;
  50. }
  51. if(v) C.push_back(v);
  52. return C;
  53. }
  54. };

进行乘法运算的时间复杂度为:Leetcode 43. 字符串相乘 - 图2,进行加法的操作的时间复杂度为Leetcode 43. 字符串相乘 - 图3,所以时间复杂度为:Leetcode 43. 字符串相乘 - 图4

优化版竖式相乘

image.png
两数相乘,结果的最大长度为m+n,位于i和j的两个数相乘,结果一定在result[i+j]和result[i+j+1],其中前者是高位,这样就大大降低了时间复杂度,变为Leetcode 43. 字符串相乘 - 图6

class Solution {
public:
    string multiply(string num1, string num2) {
        int m = num1.length(), n = num2.length();
        if(num1[0]=='0'||num2[0]=='0') return "0";
        vector<int> res(m+n,0);

        for(int i=num1.length()-1;i>=0;i--){
            int n1 = num1[i]-'0';
            for(int j=num2.length()-1;j>=0;j--){
                int n2 = num2[j]-'0';
                res[i+j] += (res[i+j+1]+n1*n2)/10;
                res[i+j+1] = (res[i+j+1]+n1*n2)%10;
            }
        }
        string s = "";
        int i = 0;
        while(res[i]==0&&i<res.size()) i++;
        for(;i<res.size();i++){
            s += res[i]+'0';
        }
        return s;

    }
};