본문 바로가기
프로그래머스 코딩테스트 연습

[프로그래머스 코테 C#] Lv1. x만큼 간격이 있는 n개의 숫자

by 노재두내 2024. 3. 21.

문제

함수 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]

주어진 코드

public class Solution {
    public long[] solution(int x, int n) {
        long[] answer = new long[] {};
        return answer;
    }
}

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

오류 

근데 뭔가 형이 다르니까 리스트는 long값, x는 int 니까 Convert로 형변환..? 가능할진 모르겠지만 해봄

using System;

public class Solution {
    public long[] solution(int x, int n) {
        long[] answer = new long[] {};
        for(int i=0;i<n;i++)
        {
            long a=Convert.ToLong(x);
            answer[i]=a;
            a+=a;
        }
        return answer;
    }
}

ㅇㅕ

역시나 Tolong은 없다고 나옴

 

명시적 형변환으로 해봄

using System;

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

여전히 indexoutofRange

 

 

 

long[] answer = new long[] {};  ==> long[] answer = new long[n];

using System;

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

 

이렇게 바꾸니 오류가 사라졌다.

다만 답은 틀림

흠 왜 a값이 증가 안했지?

아 계속 초기화 하고 있었구나

 

저부분을 for문 밖으로 뺌 그래도 틀림

이번에는 일정한 값을 더하는게 아니라 증가한 값을 더하게 되니까.. 

 

 

[나의 풀이]

using System;

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

결론적으론 i를 곱해서 하는거로 했다.

오예 통과 ~.~

 

형변환이 중요한 문제였던듯?


[다른사람풀이]

public class Solution {
    public long[] solution(int x, int n) {
            long[] answer = new long[n];

            for (int i = 0; i < n; i++)
            {
                if (i == 0)
                    answer[i] = x;
                else
                    answer[i] = x + answer[i - 1];
            }

            return answer;

    }
}

그 전 배열의 값에 x를 더함