LeetCode 43 通俗易懂 字符串相乘 一个简单的例子描述过程

LeetCode 43 字符串相乘 举一个简单的例子

 /**
    num1的第i位(高位从0开始)和num2的第j位相乘的结果在乘积中的位置是[i+j, i+j+1]
    例: 123 * 45,  123的第1位 2 和45的第0位 4 乘积 08 存放在结果的第[1, 2]位中
      index:    0 1 2 3 4  
          
                    1 2 3
                *     4 5
                ---------
                      1 5
                    1 0
                  0 5
                ---------
                  0 6 1 5
                    1 2
                  0 8
                0 4
                ---------
                0 5 5 3 5
    这样我们就可以单独都对每一位进行相乘计算把结果存入相应的index中 
class Solution {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.size()-1;
        int len2 = num2.size()-1;
        if(len1<0 || len2<0)
            return "";
        vector<int> num(len1+len2+2,0);
        for(int i=len1;i>=0;i--)
        {
            for(int j =len2;j>=0;j--)
            {
                int temp = (num1[i]-'0') * (num2[j]-'0');
                temp = temp + num[i+j+1];
                num[i+j] += temp/10;              // 注意  一个是+=  一个是=
                num[i+j+1] = temp % 10;
            }
        }
        int index = 0;
        string res = "";
        while(index < num.size() && num[index] == 0)
            index++;
        if(index == num.size())
            return "0";
        for(;index<num.size();index++)
            res+=to_string(num[index]);
        return res;
    }
};

发布了17 篇原创文章 · 获赞 17 · 访问量 460

猜你喜欢

转载自blog.csdn.net/weixin_42134034/article/details/102464635