美文网首页算法每日一题
算法题:43. 字符串相乘(leetcode)

算法题:43. 字符串相乘(leetcode)

作者: 死亡中走出来 | 来源:发表于2021-05-27 14:56 被阅读0次

看到这道题,觉得挺有意思的。怎么说呢?就是个数学问题,然后如何处理。

如题所示:

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

先找边界,看说明文件,如下:
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理

首先,判断这2个字符串是不是0,如果是,就返回。
其次,数学运算,题中说不能用大整数来,那就是大整数的转换方式,存储。
最后,跳过那些开头为0的字符;存到一个字符串,返回。
代码如下所示:

string multiply(string num1, string num2) {
        // handle edge-case where the product is 0
        if (num1 == "0" || num2 == "0") return "0";
        
        // num1.size() + num2.size() == max no. of digits
        vector<int> num(num1.size() + num2.size(), 0);
        
        // build the number by multiplying one digit at the time
        for (int i = num1.size() - 1; i >= 0; --i) {
            for (int j = num2.size() - 1; j >= 0; --j) {
                num[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
                num[i + j] += num[i + j + 1] / 10;
                num[i + j + 1] %= 10;
            }
        }
        
        // skip leading 0's
        int i = 0;
        while (i < num.size() && num[i] == 0) ++i;
        
        // transofrm the vector to a string
        string res = "";
        while (i < num.size()) res.push_back(num[i++] + '0');
        
        return res;
    }

相关文章

网友评论

    本文标题:算法题:43. 字符串相乘(leetcode)

    本文链接:https://www.haomeiwen.com/subject/rbtdsltx.html