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

43. Multiply Strings

时间:2016-02-29 07:03:19      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

把两个数反过来算

 

 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

43. Multiply Strings

标签:

原文地址:http://www.cnblogs.com/warmland/p/5226227.html

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