码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Multiply Strings

时间:2014-12-07 12:38:10      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41785759

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!