본문 바로가기

프로그래머스/lv1

자연수 뒤집어 배열로 만들기

/* 자연수 뒤집어 배열로 만들기
 * 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요.
 * 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
 *
 * n        return
 * 12345    [5,4,3,2,1]
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class programmer_1_11 {
    static long a1 = 12345;
    public int[] solution(long n) {
        int[] answer = new int[(Long.toString(n)).length()];
        String[] ar = (Long.toString(n)).split("");
        int idx = 0;
        for(int i = ar.length-1; i >= 0; i--){
            answer[idx] = Integer.parseInt(ar[i]);
            idx++;
        }
        /*  다른사람 풀이법
        String a = "" + n;
        int[] answer = new int[a.length()];
        int cnt=0;
        while(n>0) {
            answer[cnt]=(int)(n%10);
            n/=10;
            System.out.println(n);
            cnt++;
        }
         */
        return answer;
    }
    public static void main(String args[]){
        programmer_1_11 t = new programmer_1_11();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv1' 카테고리의 다른 글

문자열 내 p와 y의 개수  (0) 2022.12.13
정수 제곱근 판별  (0) 2022.12.13
자릿수 더하기  (0) 2022.12.08
평균 구하기  (0) 2022.12.08
약수의 합  (0) 2022.12.08