문제 설명

자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.

제한 조건

  • n은 10,000,000,000이하인 자연수입니다.

풀이

import java.util.*;

class Solution {
    public int[] solution(long n) {
        List<Integer> tempList = new ArrayList<>();
        
        int num = 0; // 한자리씩 숫자를 담을 변수
        
        while (n != 0) {
            num = Math.toIntExact(n % 10); // 한자리씩 long에서 int로 데이터타입 변환 후 담는다.
            tempList.add(num); // ArrayList에 담는다.
            n = n / 10; // 마지막 자리 숫자를 제거한다.
        }
        
        int[] answer = tempList.stream().mapToInt(Integer::intValue).toArray(); // ArrayList에서 array로 변환

        return answer;
    }
}

카테고리:

업데이트:

댓글남기기