43. Multiply Strings

把两个数反过来算

 

 1     public String multiply(String num1, String num2) {
 2     if(num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) {
 3             return "";
 4         }
 5         if(num1.equals("0") || num2.equals("0")) {
 6             return "0";
 7         }
 8         StringBuilder n1 = new StringBuilder(num1);
 9         n1 = n1.reverse();
10         StringBuilder n2 = new StringBuilder(num2);
11         n2 = n2.reverse();
12         int[] digit = new int[num1.length()+ num2.length() - 1];
13         for(int i = 0; i < n1.length(); i++) {
14             for(int j = 0; j < n2.length(); j++) {
15                 digit[i + j] += ((int)n1.charAt(i)- '0') * ((int)n2.charAt(j) - '0');
16             }
17         }
18         int carry = 0;
19         StringBuilder res = new StringBuilder();
20         for(int i = 0 ; i < digit.length; i++) {
21             System.out.println(digit[i]);
22         }
23         for(int i = 0; i < digit.length; i++) {
24             int temp = digit[i] + carry;
25             res.insert(0, temp % 10);
26             carry = temp / 10;
27         }
28         if(carry != 0) {
29             res.insert(0, carry);
30         }
31         int i = 0; 
32         while(i < res.length() && res.charAt(i) == '0') {
33             res.deleteCharAt(i);
34         }
35         return res.toString().equals("") ? "": res.toString();
36     }

ref: https://zhongyinzhang.wordpress.com/2014/03/13/multiply-strings/r

posted @ 2016-02-29 03:34  warmland  阅读(129)  评论(0编辑  收藏  举报