호비시의 끄적끄적
정수 내림차순으로 배치하기 본문
https://programmers.co.kr/learn/courses/30/lessons/12933
- 정수 내림차순으로 배치하기
문제 설명
함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.
제한 조건- n은 1이상 8000000000 이하인 자연수입니다.
n | return |
118372 | 873211 |
해결 흐름
1. 문자의 자리수 체크 -> 배열의 크기 할당을 위해
2. 입력받은 문자 하나씩 배열에 넣음
3. 배열에서 하나씩 꺼내 답에 더함
import java.util.Arrays;
class Solution {
public long solution(long n) {
long answer = 0;
long tmp = n;
int size = 0 ;
while(tmp>0){
tmp=tmp/10;
size++;
}
int[] num_arr = new int[size];
for(int i = 0 ; i<size; i++){
num_arr[i] = (int)(n%10);
n = n/10;
}
Arrays.sort(num_arr);
for(int i = size-1 ; i>=0; i--){
answer = answer *10;
answer += num_arr[i];
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
두 개 뽑아서 더하기 (0) | 2022.03.14 |
---|---|
하샤드 수 (0) | 2022.03.14 |
완주하지 못한 선수 (0) | 2022.03.12 |
문자열 내 p와 y의 개수 (0) | 2022.03.11 |
평균 구하기 (0) | 2022.03.11 |
Comments