【发布时间】:2022-01-03 15:19:54
【问题描述】:
我一直在尝试 leetcode 1822. Sign Of the Product of an array 的一个问题
有一个函数signFunc(x)返回:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
给你一个强文本和整数数组 nums。设乘积为数组 nums 中所有值的乘积。
返回 signFunc(product)。
示例 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
这是我解决问题的方法
class Solution {
public int arraySign(int[] nums) {
double product=1;
for(int i=0;i<nums.length;i++){
product=product*nums[i];
}
if(product>0) return 1;
else if (product <0) return -1;
else return 0;
}
}
问题是每当我将产品作为数据类型 double 时,我的所有测试用例都通过了,但是当我使用它时,只要我的测试用例失败。
**Input:**[9,72,34,29,-49,-22,-77,-17,-66,-75,-44,-30,-24]
**Output:** 1
**Expected:** -1
谁能告诉我为什么会这样???
【问题讨论】:
-
提示:你实际上不需要为这个任务做任何乘法。您需要做的就是计算数组中负元素的数量(并在 tje 数组中看到
0时立即返回0)。 -
正是 Joachim 所说的。对于任何两个负数,乘积都是正数。因此,只有遇到 odd 负数时,乘积才是负数。