|
| 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 | +varmultiply=function(num1,num2){ |
| 19 | +varm=num1.length; |
| 20 | +varn=num2.length; |
| 21 | +vararr=newArray(m+n).fill(0); |
| 22 | +for(vari=m-1;i>=0;i--){ |
| 23 | +for(varj=n-1;j>=0;j--){ |
| 24 | +varmul=(num1[i]-'0')*(num2[j]-'0'); |
| 25 | + |
| 26 | +varsum=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 | +varstr=arr.reduce((a,b)=>{ |
| 34 | +if(a===''&&b===0)returna; |
| 35 | +returna+b; |
| 36 | +},''); |
| 37 | + |
| 38 | +returnstr ?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 | + |