leetcode 43 Multiply Strings

Posted liuqiujie

tags:

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

1. 

class Solution {
public:
    string multiply(string num1, string num2) {
        string str;
        int len1=num1.size(),len2=num2.size();
        for(int i=len1-1;i>=0;--i) {
            int n1=num1[i]-0;
            if(!n1) continue;
            for(int j=len2-1;j>=0;--j) {
                int n2=num2[j]-0;
                if(!n2) continue;
                string sum=to_string(n1*n2);
                int k=len1-1-i+len2-1-j;
                while(k--) sum+=0;
                addstring(str,sum);
            }
        }
        return str.empty()?"0":str;
    }
    void addstring(string& str1,string &str2) {
        int k=0,i=0;
        reverse(str1.begin(),str1.end());
        reverse(str2.begin(),str2.end());
        for(i=0;i<str1.size()&&i<str2.size();++i) {
            int sum=str1[i]-0+str2[i]-0+k;
            str1[i]=sum%10+0;
            k=sum/10;
        }
        for(;i<str1.size();++i) {
            if(!k) break;
            int sum=str1[i]-0+k;
            str1[i]=sum%10+0;
            k=sum/10;
        }
        for(;i<str2.size();++i) {
            int sum=str2[i]-0+k;
            str1+=(sum%10+0);
            k=sum/10;
        }
        if(k) str1+=1;
        reverse(str1.begin(),str1.end());
    }
};

 

以上是关于leetcode 43 Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode43. Multiply Strings

LeetCode 43. Multiply Strings

<LeetCode OJ> 43. Multiply Strings

LeetCode题意分析&解答43. Multiply Strings

LeetCode 43. Multiply Strings

Leetcode 43: Multiply Strings