[프로그래머스/181888] n개 간격의 원소들

☑️ 문제

프로그래머스 181888

☑️ 풀이

  • 쉬웠지만 처음에 answer 배열의 크기를 구할 때 Math.ceil(num_list.length / n) 로 해서 정수 나눗셈으로 처리가 되어 문제가 발생했다. 다음 번에도 이 부분을 조심해야겠다.
//시간: 3.16ms
//메모리: 84.9MB

import java.util.*;

class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[(int) Math.ceil((double) num_list.length / n)];

        int idx = 0;
        for (int i = 0; i < num_list.length; i+=n) {
            answer[idx++] = num_list[i];
        }
        return answer;
    }
}

☑️ 문법 정리 - 반올림/올림/내림

Math.round()

  • 주어진 값을 반올림한다.
  • Math.round(float a)long 반환
  • Math.round(double a)long 반환
System.out.println(Math.round(3.5));  // 4
System.out.println(Math.round(3.4));  // 3
System.out.println(Math.round(-3.5)); // -3

Math.ceil()

  • 주어진 값을 올림하여 가장 가까운 정수로 반환한다.
  • Math.ceil(double a)double 반환
System.out.println(Math.ceil(3.1));   // 4.0
System.out.println(Math.ceil(-3.1));  // -3.0
System.out.println(Math.ceil(3.0));   // 3.0

Math.floor()

  • 주어진 값을 내림하여 가장 가까운 정수로 반환한다.
  • Math.floor(double a)double 반환
System.out.println(Math.floor(3.9));   // 3.0
System.out.println(Math.floor(-3.9));  // -4.0
System.out.println(Math.floor(3.0));   // 3.0

© 2021. All rights reserved.

yaejinkong의 블로그