There is a function
signFunc(x)
that returns:
1
ifx
is positive.-1
ifx
is negative.0
ifx
is equal to0
.
You are given an integer array
nums
. Letproduct
be the product of all values in the arraynums
.
ReturnsignFunc(product)
.
Constraints:
1 <= nums.length <= 1000
-100 <= nums[i] <= 100
這裡有一個函式
signFunc(x)
回傳:
- 如果
x
是正數回傳1
。- 如果
x
是負數回傳-1
。- 如果
x
等於0
回傳0
。
你會收到一個整數陣列
nums
。讓product
成為所有陣列nums
值的乘積。
回傳signFunc(product)
。
限制:
1 <= nums.length <= 1000
-100 <= nums[i] <= 100
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
0
乘積必定為 0
class Solution {
public:
int arraySign(vector<int>& nums) {
int sign = 1;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] == 0)
return 0;
else if(nums[i] < 0)
sign *= -1;
}
return sign;
}
};
LeetCode
C++