首页 > 代码库 > [leetcode]Multiply Strings

[leetcode]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.


基本思路:

大数乘法,此题如果用java的BigInteger做很简单,但有投机取巧之嫌,也没有达到写算法的目的。下面给出的C++代码是用基本算法思路来解决这道题。

代码:

import java.math.BigInteger;  //Java
public class Solution {
   public String multiply(String num1, String num2) {
		BigInteger temp1 = new BigInteger(num1);
		BigInteger temp2 = new BigInteger(num2);
		BigInteger result = temp1.multiply(temp2);
		return result.toString();
        
    }
}

C++基本算法

   string multiply(string num1, string num2) {  //C++

        unsigned int l1=num1.size(),l2=num2.size();
        if (l1==0||l2==0) return "0";

        vector<int> v(l1+l2,0);

        for (unsigned int i=0;i<l1;i++){
            int carry=0;
            int n1=(int)(num1[l1-i-1]-'0');//Calculate from rightmost to left
            for (unsigned int j=0;j<l2;j++){
                int n2=(num2[l2-j-1]-'0');//Calculate from rightmost to left

                int sum=n1*n2+v[i+j]+carry;
                carry=sum/10;
                v[i+j]=sum%10;
            }
            if (carry>0)
                v[i+l2]+=carry;

        }
        int start=l1+l2-1;
        while(v[start]==0) start--;
        if (start==-1) return "0";

        string s="";
        for (int i=start;i>=0;i--)
            s+=(char)(v[i]+'0');
        return s;
    }


[leetcode]Multiply Strings