Leetcode: 43.Multiply Strings(Week11, Medium)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linwh8/article/details/78572681

注:本题使用的是高精度乘法的思路


Leetcode 43
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:
(1)The length of both num1 and num2 is < 110.
(2)Both num1 and num2 contains only digits 0-9.
(3)Both num1 and num2 does not contain any leading zero.
(4)You must not use any built-in BigInteger library or convert the inputs to integer directly.

  • 题意:实现字符串的乘法。这道题本质上就是高精度乘法
  • 思路:类似于手算的思路,将之编写成代码即可
  • 算法
    • 定义一个结果字符串,该字符串的长度最大为两个字符串的长度之和
    • 判断两个字符串的长度大小,如果按照手算的思路,短的字符串应作为外层循环,长的字符串作为内层的循环
    • 对于结果的每一位,由乘积加上进位取余,再加上该位原来的值,再取余得到该位(如果该位超过10,则进位需要加一)
    • 对于进位,由乘积加上进位除以10得到,而且需要判断是否需要+1(在上一步中提到)
    • 在每一轮内层循环执行结束后,不要忘记加上余数
    • 最后需要去除无效的零位

代码如下:

class Solution {
public:
    string multiply(string num1, string num2) {
        if (num1.size() > num2.size()) {
            string temp = num1;
            num1 = num2;
            num2 = temp;
        }
        string sum(num1.size()+num2.size(), '0');
        for (int i = num1.size()-1; i >= 0; i--) {
            int carry = 0;
            int count = num1.size()+num2.size()-(num1.size()-1-i);
            count--;
            for (int j = num2.size()-1; j >= 0; j--) {
                //cout << "count: " << count << endl;
                int mul = (num2[j]-'0')*(num1[i]-'0')+carry;
                //cout << "mul: " << mul << endl;
                int temp = sum[count]-'0';
                sum[count] = ((sum[count]-'0')+(mul % 10)) % 10 + '0';
                //cout << "sum[count]: " << sum[count] << endl;
                carry = mul / 10;
                if ((temp+(mul % 10))/10 > 0) carry++;
                //cout << "carry: " << carry << endl;
                count--;
                if (j == 0) sum[count] = carry+'0';
            }
        }
        int index = -1;
        //cout << "sum: " << sum << endl;
        for (int i = 0; i < sum.size(); i++) {
            if (sum[i] == '0') index = i;
            if (sum[i] != '0') break;
        }
        if (index == sum.size()-1) sum = "0";
        else if (index != -1) sum = sum.substr(index+1);
        //cout << index << "   " << sum << endl;
        return sum;
    }
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


猜你喜欢

转载自blog.csdn.net/linwh8/article/details/78572681