
for문 대신 while문을 사용해야 한다. split을 할 경우에는 문자열 사이에 공백(" ")을 추가해주어야 두자리 이상 숫자를 배열에 넣을 수 있다.//나의 풀이
class Solution {
public int[] solution(int n) {
String str = n + " ";
while(n != 1){
if(n % 2 == 0){ //짝
n /= 2;
} else { //홀
n = 3 * n + 1;
}
str += n + " ";
}
String[] arr = str.split(" ");
int[] answer = new int [arr.length];
for(int i=0 ; i<answer.length ; i++){
answer[i] = Integer.parseInt(arr[i]);
}
return answer;
}
}
다양한 풀이 방법이 있어서 가져와 봤다. 내 풀이가 가장 쉽게 풀 수 있지만 아래의 기발한 풀이방법으로도 도전해봐야겠다.
import java.util.ArrayList;
class Solution {
public int[] solution(int n) {
ArrayList<Integer> list = new ArrayList<>();
while (n > 1) {
list.add(n);
n = n % 2 == 0 ? (n / 2) : (3 * n + 1);
}
list.add(1);
return list.stream().mapToInt(i -> i).toArray();
}
}
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[] solution(int n) {
Queue<Integer> answer = new LinkedList<>();
while (n > 1) {
answer.add(n);
if (n % 2 == 0) n >>= 1;
else n = n * 3 + 1;
}
answer.add(1);
return answer.stream().mapToInt(i -> i).toArray();
}
}
import java.util.stream.IntStream;
class Solution {
public int[] solution(int n) {
return IntStream.concat(
IntStream.iterate(n, i -> i > 1, i -> i % 2 == 0 ? i / 2 : i * 3 + 1),
IntStream.of(1))
.toArray();
}
}
while문 을 통해 1이 나올때까지 문자열에 계속 더해주고 1이 나올때 반복문을 빠져나와서 문자열을 split하여 각 숫자를 배열에 저장하여 출력.stream()을 사용한 풀이는 다시 한번 도전해봐야겠다