코딩테스트 풀이/JAVA
[LeetCode/Easy] 1822. Sign of the Product of an Array
무지맘
2023. 1. 5. 22:47
1. Input
1) 정수 배열 nums
2. Output
1) nums의 모든 요소를 곱한 값의 sign funcion의 값
// signFunction(x)
- x>0 -> 함수 값은 1
- x=0 -> 함수 값은 0
- x<0 -> 함수 값은 -1
3. Constraint
1) 1 <= nums.length <= 1000
2) -100 <= nums[i] <= 100
4. Example
Input: nums = [-1,1,-1,1,-1] -> Output: -1
Input: nums = [-1,-2,-3,-4,3,2,1] -> Output: 1
5. Code
1) 첫 코드(2022/06/24)
int numOfneg = 0;
for(int i=0 ; i<nums.length ; i++){
if(nums[i]<0) numOfneg++;
else if(nums[i]==0) return 0;
}
return numOfneg%2==0 ? 1 : -1;
- 숫자를 계속 곱해나가면 int, long의 범위를 넘어가게돼 잘못된 결과가 반환된다. 때문에 단순 곱셈 계산으로 문제를 풀려고 하면 안된다.