문제 설명
함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.
제한 조건
- x는 -10000000 이상, 10000000 이하인 정수입니다.
- n은 1000 이하인 자연수입니다.
입출력 예
x | n | answer |
2 | 5 | [2,4,6,8,10] |
4 | 3 | [4,8,12] |
-4 | 2 | [-4, -8] |
해결 과정
n이라는 배열의 길이가 있기 때문에 ArrayList 를 굳이 사용하지 않고 구하여도 되지만, ArraysList를 사용해서 풀어보고 싶었다.
x를 long 타입으로 강제 형변환을 해주어야 에러 없이 돌아간다.
정답 코드
import java.util.ArrayList;
class Solution {
public long[] solution(int x, int n) {
ArrayList<Long> answer = new ArrayList<>();
for(int i=0; i<n; i++) {
answer.add(x+(i*(long)x));
}
return answer.stream().mapToLong(i->i).toArray();
}
}
이클립스용 실행 코드
package Level1; // https://programmers.co.kr/learn/courses/30/lessons/12954
import java.util.ArrayList;
import java.util.Arrays;
public class n_Number_Increase_x {
public static void main(String[] args) {
int x = 2;
int n = 5;
long[] ans = solution(x, n);
System.out.println(Arrays.toString(ans));
}
private static long[] solution(int x, int n) {
ArrayList<Long> answer = new ArrayList<>();
for(int i=0; i<n; i++) {
answer.add(x+(i*(long)x));
}
return answer.stream().mapToLong(i->i).toArray();
}
}
'프로그래머스 > JAVA' 카테고리의 다른 글
프로그래머스) 예산 (JAVA) (0) | 2020.10.09 |
---|---|
프로그래머스) 직사각형 별찍기 (JAVA) (0) | 2020.10.09 |
프로그래머스) 행렬의 덧셈 (JAVA) (0) | 2020.10.09 |
프로그래머스) 핸드폰 번호 가리기 (JAVA) (0) | 2020.10.09 |
프로그래머스) 하샤드 수 (JAVA) (0) | 2020.10.09 |