[Programmers] x만큼 간격이 있는 n개의 숫자 - 연습문제

동민·2021년 3월 10일
0
import java.util.ArrayList;

// x만큼 간격이 있는 n개의 숫자 - 연습문제
public class IntervalX_NumN {

	// Array
	public long[] solution1(int x, int n) {

		long[] arr = new long[n];
		for(long i = 1; i <= n; i++) { // 오버플로우 주의. i를 long타입으로 해주어야함
			arr[(int)i-1] = x * i; // i 가 오버플로우 처리를 위해 long타입으로 선언됐으므로 i를 int타입으로 캐스팅 해주어야 배열의 인덱스로 사용할 수 있다.
		}
		return arr;
	}
	
	// ArrayList
	public long[] solution(int x, int n) {

		ArrayList<Long> list = new ArrayList<>(); // 문제 조건에서 x의 범위가 10000000 까지 가능하며 n은 1000 이하이면 되므로 오버플로우가 날수 있다. 따라서
													// list를 Long 타입으로 구현해야함

		for (long i = 1; i <= n; i++) {
			list.add(x * i);
		}
		return list.stream().mapToLong(i -> i.longValue()).toArray();
	}

	public static void main(String[] args) {

		IntervalX_NumN s = new IntervalX_NumN();

		for (int i = 0; i < s.solution(2, 5).length; i++) {
			System.out.print(s.solution(2, 5)[i] + " ");
		}
		System.out.println();
		for (int i = 0; i < s.solution(4, 3).length; i++) {
			System.out.print(s.solution(4, 3)[i] + " ");
		}
		System.out.println();
		for (int i = 0; i < s.solution(-4, 2).length; i++) {
			System.out.print(s.solution(-4, 2)[i] + " ");
		}

	}
}
  • 오버플로우 주의
  • long (primitive Type), Long (Class) long은 기본자료형이며 Long은 클래스 타입. 제네릭에는 long이 아니라 Long이 들어간다
profile
BE Developer

0개의 댓글