Home Leetcode 1822 - Sign of the Product of an Array
Post
Cancel

Leetcode 1822 - Sign of the Product of an Array

Link to problem

Problem

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).

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;
    }
};
This post is licensed under CC BY 4.0 by the author.