数组中一个元素和其余部分的相等划分 - JavaScript
我们需要编写一个函数,如果我们可以将数组划分为一个元素和其余部分,使得此元素等于排除它自身的其他所有元素的乘积,则返回 true,否则返回 false。
例如:如果数组为 −
const arr = [1, 56, 2, 4, 7];
则输出应为 true
因为,56 等于 −
2 * 4 * 7 * 1
示例
代码如下 −
const arr = [1, 56, 2, 4, 7];
const isEqualPartition = arr => {
const creds = arr.reduce((acc, val) => {
let { prod, max } = acc;
if(val > max || !max){
prod *= (max || 1);
max = val;
}else{
prod *= val;
}
return { prod, max };
}, {
prod: 1,
max: null
});
return creds.max === creds.prod;
};
console.log(isEqualPartition(arr));输出
控制台中的输出如下 −
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP