자연수 뒤집어 배열로 만들기 문제
https://programmers.co.kr/learn/courses/30/lessons/12932
문제설명
자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
제한조건
- n은 10,000,000,000이하인 자연수입니다.
입출력 예
n return 12345 [5,4,3,2,1]
class Solution {
public int[] solution(long n) {
String str = String.valueOf(n);
int length = str.length();
int[] answer = new int[length];
int index= 0;
for(int i = length -1; i >= 0; i--){
answer[index] = Integer.parseInt(String.valueOf(str.charAt(i)));
index++;
}
return answer;
}
}
n%10을 answer 배열에 입력 후 n/10을 반복하여 푸는 방법도 있다는 것을 알게 되었다.(숫자를 자르는게 있으면 %와 /도 염두해두자!)