[프로그래머스/Java] Lv.0 마지막 두 원소

febCho·2024년 3월 3일
0

코딩테스트

목록 보기
26/253
post-thumbnail

문제

정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.

- 제한사항

  • 2 ≤ num_list의 길이 ≤ 10
  • 1 ≤ num_list의 원소 ≤ 9

풀이

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length + 1];
        
        int last = num_list[num_list.length - 1];
        int bef_last = num_list[num_list.length - 2];
        
        for(int i=0;i<num_list.length;i++){
            answer[i] = num_list[i];
            
            if(last > bef_last){
                answer[num_list.length] = last - bef_last;
            }else{
                answer[num_list.length] = last * 2;
            }
        }
        
        return answer;
    }
}

결과

결과

profile
Done is better than perfect.

0개의 댓글