Problem
There is a function signFunc(x) that returns:
1ifxis positive.-1ifxis negative.0ifxis equal to0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
Approach (Rant) and Solution
This is the problem that I got when pressed the “Pick One” button today. Probably a bit too easy for a Leetcode easy problem.
The main problem when doing it naively, multiply all numbers and return 1, -1 or 0 accordingly, will probably overflow. Therefore, we do a if to all numbers and only save 0, 1 or -1.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int arraySign(vector<int>& nums) {
int product = 1;
for (auto n: nums) {
if (n == 0) return 0;
else if (n < 0) product *= -1;
}
return product;
}
};