43. Multiply Strings 字符串表示的大数乘法

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了43. Multiply Strings 字符串表示的大数乘法相关的知识,希望对你有一定的参考价值。

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.

 

string multiply(string& num, char ch){
    int n = ch - 0;
    string s;
    int carry = 0;
    int x;
    for(int i=num.size()-1; i>=0; i--){
        x = (num[i]-0) * n + carry;
        carry = x/10;
        s.insert(s.begin(), x%10+0); 
    }
    if (carry>0) {
        s.insert(s.begin(), carry+0);
    }
    return s;
}

string strPlus(string& num1, string& num2) {
    string s;
    int carry=0;
    int x;
    int n1 = num1.size(); 
    int n2 = num2.size(); 
    
    int i, j;
    for(i=n1-1, j=n2-1; i>=0 || j>=0; i--, j--){
        int x1 = i>=0 ?  num1[i]-0 : 0;
        int x2 = j>=0 ?  num2[j]-0 : 0;
        x = x1 + x2 + carry; 
        carry = x/10;
        s.insert(s.begin(), x%10+0);
    }
    if (carry>0) {
        s.insert(s.begin(), carry+0);
    }
    return s;
}

string multiply(string num1, string num2) {

    if (num1.size()<=0 || num2.size()<=0) return "";

    int shift=0;
    string result="0";
    for (int i=num1.size()-1; i>=0; i--) {
        string s = multiply(num2, num1[i]);        
        for(int j=0; j<shift; j++){
            s.insert(s.end(), 0);
        }
        result = strPlus(result, s);
        shift++;
    }
    //check if it is zero
    if (result[0]==0) return "0";
    return result;
}

 

以上是关于43. Multiply Strings 字符串表示的大数乘法的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 43. 字符串相乘(Multiply Strings)

<LeetCode OJ> 43. Multiply Strings

43. Multiply Strings 字符串相乘

43. Multiply Strings

LeetCode 43. 字符串相乘(Multiply Strings) 大数乘法

43. Multiply Strings