One minute
Leetcode 1822
1822. Sign of the Product of an Array
The idea of this solution is elementary:
- If the current number in
nums
is negative, then we can flip the sign - If the current number in
nums
is equal to0
, we can return0
because any number multiplied by0
is0
. You might think that we can check forif num == 0
after 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 a0
in 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