File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/multiply-strings/description/
3+ * Difficulty:Medium
4+ *
5+ * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
6+ * Note:
7+ * The length of both num1 and num2 is < 110.
8+ * Both num1 and num2 contains only digits 0-9.
9+ * Both num1 and num2 does not contain any leading zero.
10+ * You must not use any built-in BigInteger library or convert the inputs to integer directly.
11+ */
12+
13+ /**
14+ * @param {string } num1
15+ * @param {string } num2
16+ * @return {string }
17+ */
18+ var multiply = function ( num1 , num2 ) {
19+ var m = num1 . length ;
20+ var n = num2 . length ;
21+ var arr = new Array ( m + n ) . fill ( 0 ) ;
22+ for ( var i = m - 1 ; i >= 0 ; i -- ) {
23+ for ( var j = n - 1 ; j >= 0 ; j -- ) {
24+ var mul = ( num1 [ i ] - '0' ) * ( num2 [ j ] - '0' ) ;
25+
26+ var sum = mul + arr [ i + j + 1 ] ;
27+
28+ arr [ i + j ] += Math . floor ( sum / 10 ) ;
29+ arr [ i + j + 1 ] = sum % 10 ;
30+ }
31+ }
32+
33+ var str = arr . reduce ( ( a , b ) => {
34+ if ( a === '' && b === 0 ) return a ;
35+ return a + b ;
36+ } , '' ) ;
37+
38+ return str ? str : '0' ;
39+
40+ } ;
41+
42+ console . log ( multiply ( '89' , '45' ) ) ;
43+ console . log ( multiply ( '123' , '123' ) ) ;
44+ console . log ( multiply ( '123' , '0' ) ) ;
45+
46+
You can’t perform that action at this time.
0 commit comments