forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9606275
commit 921584e
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
.../02- Sign of the Product of an Array/02- Sign of the Product of an Array (Ahmed Gamal).js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// Author: Ahmed Gamal | ||
|
||
// for this problem, we just need to keep track of two important things that determine the sign of the product of the array: | ||
// 1- if the array contains a zero, then the product will be zero (regardless of the other values in the array) | ||
// 2- if the array contains an odd number of negative values, then the product will be negative, otherwise it will be positive | ||
|
||
/** | ||
* @param {number[]} nums | ||
* @return {number} | ||
*/ | ||
var arraySign = function(nums) { | ||
// odd: true if the number of negative values is odd, false otherwise | ||
// zero: true if the array contains a zero, false otherwise | ||
let odd = false, zero = false; | ||
|
||
// loop through the array and update the values of odd and zero | ||
nums.forEach(x => { | ||
// if x < 0, then odd will be true if it was false, and false if it was true (using XOR) | ||
odd ^= x < 0; | ||
|
||
// if x === 0, then zero will be true | ||
zero |= x === 0; | ||
}); | ||
|
||
// if zero is true, then the product will be zero regardless of the value of odd | ||
if(zero) { | ||
return 0; | ||
} | ||
|
||
// if odd is true, then the product will be negative, otherwise it will be positive | ||
return (odd && -1) || 1; | ||
}; |