5726. 数组元素积的符号

已知函数 signFunc(x) 将会根据 x 的正负返回特定值:

  • 如果 x 是正数,返回 1 。
  • 如果 x 是负数,返回 -1 。
  • 如果 x 是等于 0 ,返回 0 。

给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。

返回 signFunc(product) 。

 

示例 1:

输入:nums = [-1,-2,-3,-4,3,2,1]
输出:1
解释:数组中所有值的乘积是 144 ,且 signFunc(144) = 1

示例 2:

输入:nums = [1,5,0,2,-3]
输出:0
解释:数组中所有值的乘积是 0 ,且 signFunc(0) = 0

示例 3:

输入:nums = [-1,1,-1,1,-1]
输出:-1
解释:数组中所有值的乘积是 -1 ,且 signFunc(-1) = -1

 

提示:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100
package Solution5726;

import java.math.BigInteger;

class Solution {

	public int arraySign(int[] nums) {
		BigInteger product = new BigInteger("1");
		for (int i = 0; i < nums.length; i++) {
			product = product.multiply(new BigInteger(String.valueOf(nums[i])));
		}
		// System.out.println(product);
		return signFunc(product);
	}

	public int signFunc(BigInteger x) {
		if (x.compareTo(new BigInteger("0")) == 1) {
			return 1;
		}
		if (x.compareTo(new BigInteger("0")) == -1) {
			return -1;
		}
		return 0;
	}

	public static void main(String[] args) {

		Solution sol = new Solution();
		int[] nums = { 9, 72, 34, 29, -49, -22, -77, -17, -66, -75, -44, -30, -24 };
		System.out.println(sol.arraySign(nums));

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值