【LeetCode】43. Multiply Strings


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.
就是实现一个乘法,但是因为结果的值较大可能会超过类型的范围,所以用string类型来表示。
简单直接的就是模拟竖式乘法。

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1=="0" || num2=="0")
            return "0";
        
        int len1 = num1.size(),len2 = num2.size();
        string res = "";
        int pos,tem,carry = 0;
        reverse(num1.begin(),num1.end());//先对num1和num2做一个逆序,处理起来直观一些
        reverse(num2.begin(),num2.end());
        
        for(int i=0;i<len1;i++){
            pos = i;//pos表示的是这一个乘法的起始位置,每一次的起始位置由i决定
            for(int j=0;j<len2;j++){
                tem = (num1[i]-'0')*(num2[j]-'0')+carry;
                
                if(pos<res.length()){//如果当前乘法运算位置小于res的长度,那么就需要将本次乘法结果tem跟res对应pos的数做加法
                    tem = tem + (res[pos]-'0');
                    res[pos] = tem%10+'0';
                }
                else if(pos>=res.length()){//如果当前乘法运算位置大于或等于当res长度,只需要把当前乘法结果tem添加到res末尾。
                    res.append(1,(tem%10)+'0');
                }
                carry = tem/10;
                pos++;
            }
            if(carry > 0)
                res.append(1,carry%10+'0');
            carry = 0;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

不是太难的题,但是卡了好久,,,,还是需要提高。




猜你喜欢

转载自blog.csdn.net/poulang5786/article/details/80355281