[Easy] 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).

 

nums 배열의 요소들을 모두 곱했을 때 양수면 1 반환, 음수면 -1 반환, 0이면 0을 반환한다.

 

예시

Example 1:

Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1

Example 2:

Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0

Example 3:

Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1

 

제약 조건

Constraints:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100

 

해결 과정

문제 그대로 쉽게 해결할 수 있었다.

곱하는 과정 중 0이 들어있다면 더이상 계산을 하지 않고 바로 0을 반환하도록 처리해주었더니 시간이 훨씬 줄었다.

  • nums 배열의 요소들을 곱할 mul 변수를 초기화한다. 이 때, 1로 초기화를 시켜야 곱셈이 된다.
  • nums를 전체 탐색한다.
    • nums 요소들을 mul 변수에 곱한다. 
    • 이때, nums 요소가 0이라면 바로 0을 반환한다. 여러 숫자들 사이에 0이  하나라도 존재한다면 무조건 0이 되기 때문이다.
  • mul의 값이 0보다 작으면 -1 반환, 0보다 크면 1 반환, 그 외의 상황에는 0을 반환한다.

해결 코드

/**
 * @param {number[]} nums
 * @return {number}
 */
var arraySign = function(nums) {
    
    let mul = 1;
    for(let i = 0 ; i < nums.length ; i++){
        if(nums[i] === 0) return 0;
        mul *= nums[i];
    }
    
    if(mul < 0) return -1;
    else if(mul > 0) return 1;
    else return 0;
};