[LeetCode] Sign of the Product of an Array

1822. Sign of the Product of an Array

There is a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the array nums.

Return signFunc(product).

  • new solution update 2022.02.08
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int arraySign(vector<int>& nums) {
int res = 1;
for(int n :nums) {
if(n == 0) return 0;
else if(n < 0) res = -res;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int arraySign(vector<int>& nums) {
bool flag = true;
for(auto& num : nums) {
if(num < 0)
flag ^= true;
if(!num)
return 0;
}

return flag ? 1 : -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/11/PS/LeetCode/sign-of-the-product-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.