首页 > Web开发 > 详细

43. Multiply Strings(js)

时间:2019-02-24 00:37:08      阅读:156      评论:0      收藏:0      [点我收藏+]

43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"
题意:实现‘乘’运算符
代码如下:
/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var multiply = function(num1, num2) {
        let m=num1.length,n=num2.length;
        let pos=new Array(m+n).fill(0);
        for(let i=m-1;i>=0;i--){
            for(let j=n-1;j>=0;j--){
                let mul=parseInt(num1.charAt(i))*parseInt(num2.charAt(j));
                let p1=i+j,p2=i+j+1;
                let sum=mul+pos[p2];
                
                pos[p1]+=parseInt(sum/10);
                pos[p2]=sum%10;
            }
        }
        let sb=‘‘;
        for(let p of pos){
            if(!(p==0 && sb.length==0)) sb+=p;
            
        }
        return sb.length==0?"0":sb;
};

 

43. Multiply Strings(js)

原文:https://www.cnblogs.com/xingguozhiming/p/10424924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!