10行代码实现大整数乘法(js)

来自leetcode上面的高赞算法(传送门:https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation):
在这里插入图片描述
假设第一个字符串为a,第二个字符串为b,那么 a[i]*b[j] 所得的数一定是在答案的ans[i+j]和ans[i+j+1]位置处。那么接下来只需要在相应的位置再注意是否需要进位以及最后要注意去掉首位0就可以轻松得到答案。涉及到正负的话,可以先判断首位,然后对字符进行处理使其均为正,最后根据需要在答案前面添加符号即可。

代码如下(输入为非负):

function mulBig(a,b){
	let len = a.length+b.length;
	let arr = new Array(len);
	arr.fill(0); //为了进行加法运算需要先初始化为0
	for(let i=a.length-1; i>=0; i--){
    	for(let j=b.length-1; j>=0; j--){  //倒序,从个位开始计算
        	let mul  = a[i]*b[j]+arr[i+j+1];
        	arr[i+j] += Math.floor(mul/10);
        	arr[i+j+1] = mul%10;
    	}
	}
	return(arr.join("").replace(/^0+/,'')); //去掉首位0
}

猜你喜欢

转载自blog.csdn.net/xxtust/article/details/88841791