我必须将数组中所有元素的符号相乘。
例如1:
input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1
例2:
input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1
例3:
input: [1, -2, 3, 0]
output: 0
Explain: 1 * (-1) * 1 * 0 = 0
这是我的解决方案
function cal(A)
{
return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
}
但是,ex3 cal([1, -2, 3, 0])
的输出是 -0
。
我已经考虑过再添加一个这样的条件
function cal(A)
{
var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
if(total === 0)
return 0;
else
return total;
}
显然,它看起来很丑。有没有更优雅的方法来解决这个问题?
最佳答案
为了避免条件检查并保持函数纯计算性,您可以使用 -0
的奇怪规则来简单地将 0 添加到 reduce()
的结果中这对非零结果没有影响,但会产生将 -0
转换为 0
的效果。
function cal(arr) {
return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
}
console.log(cal([1, 2, 3])); // 1
console.log(cal([1, -2, 3])); // -1
console.log(cal([1, -2, 3, 0])); // 0
参见signed zero进行更一般性的讨论。
关于javascript - Javascript 中解决负零的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72781994/