leetcode------Multiply Strings

标题: Multiply Strings
通过率:  20.8%
难度: 中等

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去处理的话就没有本题的实际意义了,本题想要做的就是模拟乘法,乘法如何计算很容易判断,

难度就是模拟计算,用一个数组去储存临时的数据,然后一个进位缓存,去保存进位,本题难度就是位置的确定。

直接看代码如何处理:

 1 public class Solution {
 2     public String multiply(String num1, String num2) {
 3                   int len1=num1.length(),len2=num2.length(),numTemp1=0,numTemp2=0,carry=0,sum=0;
 4             String result="";
 5             if(len1==0||len2==0)return "0";
 6             int [] tmpArray=new int[len1+len2];
 7             int location=0;
 8             for(int i=0;i<len1;i++){
 9                 numTemp1=Integer.valueOf(num1.charAt(len1-i-1)-'0');
10                 carry=0;
11                
12                 for(int j=0;j<len2;j++){
13                     numTemp2=Integer.valueOf(num2.charAt(len2-j-1)-'0');
14                     sum=numTemp1*numTemp2+tmpArray[len1+len2-j-i-1]+carry;
15                     carry=sum/10;
16                     sum=sum%10;
17                     tmpArray[len1+len2-j-i-1]=sum;
18                     location=j;
19                 }
20                if(carry!=0)tmpArray[len1+len2-i-location-2]+=carry;
21                 
22             }
23             int start=0;
24             for(;start<len1+len2;start++){                
25                 if(tmpArray[start]!=0)break;
26             }
27             if(start==(len1+len2))return "0";
28             for(;start<len1+len2;start++){
29                 result+=tmpArray[start];
30                 
31             }
32             return result;
33             
34         
35     }
36 }

 python代码:

 1 class Solution:
 2     def multiply(self, num1, num2):
 3         num1, num2 = num1[::-1], num2[::-1]
 4         result = [0 for i in range(len(num1) + len(num2))]
 5         for i in range(len(num1)):
 6             for j in range(len(num2)):
 7                 result[i + j] += int(num1[i]) * int(num2[j])
 8         carry, total = 0, []
 9         for digit in result:
10             sum = carry + digit
11             carry = sum / 10
12             total.insert(0, str(sum % 10))
13         while len(total) > 1 and total[0] == "0":
14             del total[0]
15         return ''.join(total)

 

posted @ 2015-02-11 14:46  pku_smile  阅读(198)  评论(0编辑  收藏  举报