CODING TEST
프로그래머스 - 짝수는 싫어요
우진하다
2023. 5. 15. 20:42
나의 풀이.
변수 idx를 삼항 연산자로 배열의 크기를 구하고
변수 index를 이용해 배열의 인덱스 관리해주며 선언된 배열에 n을 포함한 홀수를 넣기
import java.util.*;
class Solution {
public int[] solution(int n) {
int idx = (n % 2 == 0) ? (n / 2) : (( n / 2) + 1);
int[] answer = new int[idx];
int answerIndex = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
continue;
}
answer[answerIndex++] = i;
}
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution st = new Solution();
System.out.println(Arrays.toString(st.solution(10))); // [1, 3, 5, 7, 9]
System.out.println(Arrays.toString(st.solution(15))); // [1, 3, 5, 7, 9, 11, 13, 15]
}
}
문제출처 : https://school.programmers.co.kr/learn/courses/30/lessons/120813?language=java