Skip to content

Commit a64fb3d

Browse files
committed
#1822: Sign of the Product of an Array; solution & tests
1 parent 654f2b8 commit a64fb3d

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* 1822
3+
* Sign of the Product of an Array
4+
**
5+
* Implement a function signFunc(x) that returns:
6+
* • 1 if x is positive.
7+
* • -1 if x is negative.
8+
* • 0 if x is equal to 0.
9+
*
10+
* You are given an integer array nums.
11+
* Let product be the product of all values in the array nums.
12+
*
13+
* Return signFunc(product).
14+
*
15+
* Example 1:
16+
* Input: nums = [-1,-2,-3,-4,3,2,1]
17+
* Output: 1
18+
* Explanation:
19+
* The product of all values in the array is 144, and signFunc(144) = 1
20+
*
21+
* Example 2:
22+
* Input: nums = [1,5,0,2,-3]
23+
* Output: 0
24+
* Explanation:
25+
* The product of all values in the array is 0, and signFunc(0) = 0
26+
*
27+
* Example 3:
28+
* Input: nums = [-1,1,-1,1,-1]
29+
* Output: -1
30+
* Explanation:
31+
* The product of all values in the array is -1, and signFunc(-1) = -1
32+
*
33+
* Constraints:
34+
* • 1 <= nums.length <= 1000
35+
* • -100 <= nums[i] <= 100
36+
*
37+
* Hint 1:
38+
* If there is a 0 in the array the answer is 0
39+
*
40+
* Hint 2:
41+
* To avoid overflow make all the negative numbers -1
42+
* and all positive numbers 1 and calculate the prod
43+
**
44+
* https://leetcode.com/problems/sign-of-the-product-of-an-array/
45+
***/
46+
47+
namespace Problems;
48+
49+
public class SignOfTheProductOfAnArray
50+
{
51+
public int ArraySign( int[] nums )
52+
{
53+
int sign = 1;
54+
55+
foreach ( int num in nums )
56+
{
57+
if ( num == 0 )
58+
{
59+
return 0;
60+
}
61+
else if ( num < 0 )
62+
{
63+
sign *= -1;
64+
}
65+
}
66+
67+
return sign;
68+
}
69+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class SignOfTheProductOfAnArrayTests
6+
{
7+
[TestCase( new int[] { -1, -2, -3, -4, 3, 2, 1 }, ExpectedResult = 1 )]
8+
[TestCase( new int[] { 1, 5, 0, 2, -3 }, ExpectedResult = 0 )]
9+
[TestCase( new int[] { -1, 1, -1, 1, -1 }, ExpectedResult = -1 )]
10+
[TestCase( new int[] { 7, 36, 96, 70, 85, 23, 5, 18, 4, 12, 89, 92, 9, 30, 53, 14, 96, 32, 13, 43, 37, 60, 75, 7, 83, 68, 20, 8, -24, -80, -27, -92, -96, -20, -16, -52, -49, -38 }, ExpectedResult = 1 )]
11+
[TestCase( new int[] { 9, 72, 34, 29, -49, -22, -77, -17, -66, -75, -44, -30, -24 }, ExpectedResult = -1 )]
12+
public int ArraySignTest( int[] nums ) =>
13+
new SignOfTheProductOfAnArray().ArraySign( nums );
14+
}

0 commit comments

Comments
 (0)