Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

 1  public class Solution {
 2     public String multiply(String num1, String num2) {
 3         if(num1.equals("0")||num2.equals("0")) return "0";
 4         int len1 = num1.length();
 5         int len2 = num2.length();
 6         int carry = 0;
 7         int [] res = new int[len1+len2];
 8         for(int i=len1-1;i>=0;i--){
 9             carry=0; //don't forget this
10             int digit1 = num1.charAt(i)-'0';
11             for(int j=len2-1;j>=0;j--){
12                 int digit2 = num2.charAt(j)-'0';
13                 res[i+j+1] +=carry+digit2*digit1;
14                 carry = res[i+j+1]/10;
15                 res[i+j+1] %=10;
16             }
17             if(carry>0){
18                 res[i]=carry;
19             }
20         }
21         StringBuilder sb = new StringBuilder();
22         if(carry>0){
23             res[0]=carry;
24             for(int i=0;i<res.length;i++){
25                 sb.append(res[i]);
26             }
27         }
28         else{
29             for(int i=1;i<res.length;i++){
30                 sb.append(res[i]);
31             }
32         }
33         return sb.toString();
34     }
35 }
View Code

 if(num1.equals("0")||num2.equals("0")) return "0";

posted @ 2014-02-06 14:17  krunning  阅读(118)  评论(0编辑  收藏  举报