study/Algorithm

[프로그래머스/Java] x만큼 간격이 있는 n개의 숫자

으녕오리 2025. 3. 12. 17:05

핵심 정리

  • 정수형 자료형을 크기별로 나열하면, byte < short < int < long
    • int의 표현 범위 : -2,147,483,648  ~ 2,147,483,647
  • 자동 형변환 시 데이터 손실이 없어야 하므로, 큰 크기의 자료형 -> 작은 크기의 자료형 만 가능
    • 연산 전에 int인 x를 long으로 형변환 해줘야 한다.(명시적 형변환 필요)

 

문제

 

나의 풀이

class Solution {
    public static int[] solution(int x, int n) {
        int[] result = new int[n];
        
        for (int i = 0; i < n; i++) {
            result[i] = x * (i + 1);
        }
        return result;
    }
}

 

틀린 이유

문제의 제한조건에 따라 풀면 계산 결과가 자바의 int의 표현 범위를 넘어가는 경우가 발생한다.

따라서, 풀이에 int 대신 long 타입을 사용해줘야 한다.

 

정답

class Solution {
    public static long[] solution(int x, int n) {
        long[] result = new long[n];
        
        for (int i = 0; i < n; i++) {
            result[i] = (long) x * (i + 1);
        }
        return result;
    }
}

'study > Algorithm' 카테고리의 다른 글

[프로그래머스/Java] 폰켓몬  (0) 2025.03.10
[프로그래머스/Java] 짝수의 합  (0) 2025.02.20