One minute
Leetcode 1822
1822. Sign of the Product of an Array
The idea of this solution is elementary:
- If the current number in
numsis negative, then we can flip the sign - If the current number in
numsis equal to0, we can return0because any number multiplied by0is0. You might think that we can check forif num == 0after we have iterated, but that won’t work because we only switch the sign and don’t multiply by0, so we will never know whether there is a0in the array.
func arraySign(nums []int) int {
sign := 1
for _, num := range nums {
if num <= -1 {
sign = - sign
} else if num == 0 {
return 0
}
}
return sign
}
Read other posts