내 풀이
import java.util.*;
class Solution {
public int[] solution(int n) {
int count = 1;
List<Integer> list = new ArrayList<>();
while(count<=n){
if(count%2 == 1) {
list.add(count);
}
count++;
}
Object[] objetctList = list.toArray();
int[] newInt = new int[objetctList.length];
for (int i=0; i<objetctList.length; i++){
newInt[i] = (int)objetctList[i];
}
System.out.println("newInt = " + Arrays.toString(newInt));
return newInt;
}
}
배열로 변환도 까다롭고, 루프문을 두번써서 좋지않은 풀이이다.
다른풀이1
import java.util.List;
import java.util.ArrayList;
class Solution {
public int[] solution(int n) {
List<Integer> answer = new ArrayList<>();
for(int i=1; i<=n; i++){
if(i % 2 == 1){
answer.add(i);
}
}
return answer.stream().mapToInt(x -> x).toArray();
}
}
List를 stream 을 이용하여 배열로 만들었지만 결과적으로 두번 루프문을 사용한것은 변함이 없다.
다른풀이2
import java.util.stream.IntStream;
class Solution {
public int[] solution(int n) {
return IntStream.rangeClosed(0, n)
.filter(e -> e % 2 != 0)
.toArray();
}
}
제일 깔끔한 풀이
Intstream을 이용해 rangeClosed와 filter를 활용하여 한번에 배열로 변경하였다.