Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

高精度乘法。需要注意的是char表示的数字和int对应的数字之间的转化。

class Solution {
public:
    string multiply(string num1, string num2) {
        int l1=num1.length(),l2=num2.length();
        if(l1==0||l2==0){
            string ans="";
            return ans;
        }
        string ans(l1+l2,'0');
        for(int i=l1-1;i>=0;i--){
            int add=0;
            for(int j=l2-1;j>=0;j--){
                int t=(ans[i+j+1]-'0')+(num1[i]-'0')*(num2[j]-'0')+add;
                ans[i+j+1]=t%10+'0';
                add=t/10;
            }
            ans[i]=add+'0';
        }
        size_t s0 = ans.find_first_not_of('0');
        if(s0!=string::npos){
            return ans.substr(s0);
        }
        return "0";
    }
};

 

相关文章:

  • 2021-10-29
  • 2021-09-19
  • 2021-11-21
  • 2021-05-21
  • 2021-10-15
  • 2022-03-04
  • 2022-01-02
猜你喜欢
  • 2021-10-02
  • 2021-11-01
  • 2021-11-22
  • 2021-12-10
  • 2022-01-09
  • 2021-08-09
  • 2021-06-10
相关资源
相似解决方案