Javascript 中解决负零的优雅方法

问题描述 投票:0回答:3

我必须将数组中所有元素的符号相乘。

例如1:

input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1

例2:

input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1

Ex3:

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;
}

很明显,它看起来很丑。有没有更优雅的方法来解决这个问题?

javascript arrays algorithm zero
3个回答
2
投票

为了避免条件检查并保持函数纯粹的计算性,您可以使用

-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

请参阅带符号的零以获取更一般性的讨论。


1
投票

在您的示例中,无需将所有值相乘。如果至少有一个零,则结果为零,因此无需迭代整个数组。下面的例子:

function compute(arr)
{
    let result = true;
    for (let item of arr) {
        if (item === 0) return 0;
        if (item < 0) result = !result;
    }
    return result ? 1 : -1;
}

console.log(compute([1, 2, 3]));
console.log(compute([1, -2, 3]));
console.log(compute([1, -2, 3, 0]));


0
投票

我的代码检查是否,如果数组包含0,则结果将始终为0,无论其他元素的符号如何。对于所有其他情况,它将像以前一样计算符号的乘积。

function cal(A) {
  return A.reduce((total, currentValue) => {
    if (currentValue === 0) {
      return 0; // if 0 in array return 0
    }
    return total * Math.sign(currentValue);
  }, 1);
}
console.log(cal([1, 2, 3]))       // 1
console.log(cal([1, -2, 3]));     //-1
console.log(cal([1, -2, 3, 0]));  // 0
.as-console-wrapper { max-height: 100% !important; top: 0; }

© www.soinside.com 2019 - 2024. All rights reserved.