File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .leetcode ;
2+
3+ /**
4+ * 43. 字符串相乘
5+ * 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
6+ *
7+ * 示例 1:
8+ *
9+ * 输入: num1 = "2", num2 = "3"
10+ * 输出: "6"
11+ * 示例 2:
12+ *
13+ * 输入: num1 = "123", num2 = "456"
14+ * 输出: "56088"
15+ */
16+ public class Main43 {
17+ public String multiply (String num1 , String num2 ) {
18+ if (num1 .equals ("0" ) || num2 .equals ("0" )) {
19+ return "0" ;
20+ }
21+ StringBuilder res = new StringBuilder ();
22+ int m = num1 .length ();
23+ int n = num2 .length ();
24+ int [] tmp = new int [m +n ];
25+ for (int i = m -1 ; i >= 0 ; i --) {
26+ int x = num1 .charAt (i ) - '0' ;
27+ for (int j = n -1 ; j >= 0 ; j --) {
28+ int y = num2 .charAt (j ) - '0' ;
29+ int sum = tmp [i +j +1 ] + x * y ;
30+ tmp [i +j +1 ] = sum % 10 ;
31+ tmp [i +j ] += sum / 10 ;
32+ }
33+ }
34+ for (int i = 0 ; i < m +n ; i ++) {
35+ if (i == 0 && tmp [i ] == 0 )
36+ continue ;
37+ res .append (tmp [i ]);
38+ }
39+ return res .toString ();
40+ }
41+
42+ public static void main (String [] args ) {
43+ Main43 m = new Main43 ();
44+ String num1 = "123" ;
45+ String num2 = "456" ;
46+ System .out .println (m .multiply (num1 , num2 ));
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments