본문 바로가기

컴퓨터 프로그래밍/알고리즘

프로그래머스_정수 내림차순으로 배치하기

문제 설명

함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.

제한 조건

- n은 1이상 8000000000 이하인 자연수입니다.

<내풀이>

import java.util.ArrayList;
import java.util.Collections;

public static long solution(long n) {
        long answer = 0;
        ArrayList<Long> nList = new ArrayList<>();
        while(n>10) {
        	nList.add((n%10));
        	n= n/10;
        }
        nList.add(n);
        
        Collections.sort(nList);
        
        String s = "";
        for(Long l : nList) {
        	s = l.toString()+s;
        }
        
        answer = Long.parseLong(s);        
        return answer;
    }

(Collections.sort를 이용해서 내림차순으로 정렬 할 수 있습니다. 그래서 Long type을 String으로 바꿀 때는 Long.parseLong(s)를 해줘야합니다.)

 

<남풀이>

(남풀이는 봤는데,.,, 좀.....)