【每日一题】43. Multiply Strings

作者: 七八音 | 来源:发表于2020-09-01 00:01 被阅读0次

    题目描述

    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

    Example 1:

    Input: num1 = "2", num2 = "3"
    Output: "6"
    

    Example 2:

    Input: num1 = "123", num2 = "456"
    Output: "56088"
    

    Note:

    1. The length of both num1 and num2 is < 110.
    2. Both num1 and num2 contain only digits 0-9.
    3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

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

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

    题解

    由于题目要求:不能将字符串转化成大整数来处理。所以需要换一种方法,这里打算模仿2个整数的计算过程,直接计算结果。

    模仿自己手算整数的计算:把两个数末尾对齐,固定一个数字a,从末尾开始,依次用数字与另个整数b的末尾开始相乘,计算进位数、余数;整数b遍历完成后,将指向a中的数字向前移动一位,反复计算,直到数字a遍历完成。

    值得注意的是:需要先设定一个字符串用户存储临时的结果。所以,我们要明确字符串的长度,设整数1、整数2长度分别为m,n;那么乘法结果的最大长度为m+n。两个数字都遍历完成后,对临时结果从头到尾进行遍历,舍去其中为‘0’的字符。

    完整代码:

    class Solution {
    public:
        string multiply(string num1, string num2) {
            int size1 = num1.size(), size2 = num2.size();
            string res(size1+size2, '0');
            
            for (int i=size1-1; i>=0; --i){
                for (int j=size2-1; j>=0; --j){
                    int temp = (num1[i] - '0') * (num2[j] - '0') + (res[i+j+1] - '0');
                    res[i+j] += temp / 10 ;
                    res[i+j+1] = temp % 10 + '0';
                }
            }
            
            for (int i=0; i< size1+size2; i++){
                if (res[i] != '0')
                    return res.substr(i);
            }
            return "0";
        }
    };
    

    欢迎关注公众号,一起学习

    相关文章

      网友评论

        本文标题:【每日一题】43. Multiply Strings

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