1822. Sign of the Product of an Array
Last updated
Last updated
func arraySign(nums []int) int {
var sign int8 = 1
for _, v := range nums {
if v == 0 {
return 0
}
if v < 0 {
sign *= -1
}
}
return int(sign)
}func arraySign(nums []int) int {
negativeCount := 0
// Loop through the array
for _, num := range nums {
if num == 0 {
return 0 // If any number is 0, product will be 0
}
if num < 0 {
negativeCount++ // Count negative numbers
}
}
// If there are an odd number of negative numbers, the product is negative.
if negativeCount % 2 == 0 {
return 1 // Positive product
}
return -1 // Negative product
}