43. Multiply Strings

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于43. Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章

43. Multiply Strings

#Leetcode# 43. Multiply Strings

Leetcode 43. Multiply Strings

43. Multiply Strings

43. Multiply Strings

LeetCode 43. Multiply Strings