Study with me/프로그래머스 L0 마스터하기
프로그래머스 - L0 조건에맞게수열변환하기1
외계나무
2023. 12. 8. 10:04
프로그래머스 - level 0 조건에 맞게 수열 변환하기 1
문제는 for loop로 그냥 풀었는데, IntStream을 써보고 싶어서 시도했지만 실패함. 다음은 실패한 코드...
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int[] answer = IntStream.of(arr)
.map(n -> (n>=50 && n%2==0) ? n/2 : (n<50 && n%2!=0) ? n*2 : n)
.toArray();
// ERROR...
return answer;
}
}
이건 타인의 코드. 삼항 연산자를 겹치는 것은 효율면에서는 좋지 않다고 하는데, 그것보단 stream 사용 때문에 가져옴.
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
return Arrays.stream(arr)
.map(operand -> operand >= 50 && operand % 2 == 0 ? operand / 2 : operand < 50 && operand % 2 == 1 ? operand * 2 : operand)
.toArray();
}
}