[LeetCode]#1822. Sign of the Product of an Array

Fatboy Slim
Jan 20, 2022

--

Environment: Python 3.8

Key technique: for, if

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

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

Analysis:

  1. init ans=1
  2. ans=ans x nums[i] by using loop
  3. if ans >0, return 1
  4. if ans <0, return -1
  5. if ans==0, return 0

Solution:

class Solution:
def arraySign(self, nums):
ans=1
for i in range(len(nums)):
ans=ans*nums[i]
if ans >0:
return 1
if ans <0:
return -1
if ans ==0:
return 0

Submissions:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet