카테고리 없음
[프로그래머스]#42 자연수 뒤집어 배열로 만들기
미조미
2022. 9. 4. 22:38
- 자연수 뒤집어 배열로 만들기
문제설명
자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
제한 조건- n은 10,000,000,000이하인 자연수입니다.
12345 | [5,4,3,2,1] |
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import java.util.*;
class Solution {
public int[] solution(long n) {
String str = String.valueOf(n); //n을 string으로 변경
int size = str.length() ;
int[] answer = new int[size];
int index = 0;
for(int i=size-1 ; i>=0; i--){
answer[index] = Integer.parseInt(String.valueOf(str.charAt(i)));
index ++;
}
return answer;
}
}
다른 풀이
import java.util.*;
class Solution {
public int[] solution(long n) {
int[] answer = {};
String st = String.valueOf(n);
int size = st.length();
answer = new int [size];
for(int i=0; i<st.length(); i++ ){ //12345
answer[i] = (int)n%10;
n = n/10;
}
return answer;
}
}
이렇게 숫자를 자를때는 n%10, n/10을 반복문에 넣는 방법도 있다.
String st = String.valueOf(n) 대신에
String st = ""+n 으로 대체할 수 있다.