Programmers. x만큼 간격이 있는 n개의 숫자
[문제설명]
함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.
[제한사항]
- x는 -10000000 이상, 10000000 이하인 정수입니다.
- n은 1000 이하인 자연수입니다.
if(1<= n && n<=1000 && -10000000 <= x && x<= 10000000) (해답에 기재하지 않았습니다.)
[입출력 예]
x | n | answer |
2 | 5 | [2,4,6,8,10] |
4 | 3 | [4,8,12] |
-4 | 2 | [-4, -8] |
[기본 상태]
class Solution {
public long[] solution(int x, int n) {
long[] answer = {};
return answer;
}
}
[풀이에 필요한 조건]
answer 배열에 넣어줄 값을 저장할 sum 변수 선언 (기본값 x > 배열 0번에 값 입력을 위해).
배열 반복을 위한 for 문. 최대 루프값보다 1 작은 값에서 끝나도록 설정.
answer 배열에 순서대로 sum 값을 지정하고, 다음 저장할 sum 값에 x를 더함.
( sum*(i+1) 로 바로 배열에 넣어도 무방 )
[해답]
//개인 솔루션
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
long sum=x;
for (int i = 0; i < n; i++) {
answer[i] = sum;
sum += x;
}
return answer;
}
}
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
long sum=x;
for (int i = 0; i < n; i++) {
answer[i] = sum;
sum += x;
// System.out.println(answer[i]);
}
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
long[] result1 = sol.solution(2,5);
long[] result2 = sol.solution(4,3);
long[] result3 = sol.solution(-4,2);
int n=5;
System.out.print("result1 = {");
for(int i=0;i<n;i++){
System.out.print(result1[i]);
if(i==n-1){
}
else {
System.out.print(",");
}
}
System.out.println("}");
n=3;
System.out.print("result2 = {");
for(int i=0;i<n;i++){
System.out.print(result2[i]);
if(i==n-1){
}
else {
System.out.print(",");
}
}
System.out.println("}");
n=2;
System.out.print("result3 = {");
for(int i=0;i<n;i++){
System.out.print(result3[i]);
if(i==n-1){
}
else {
System.out.print(",");
}
}
System.out.println("}");
}
}