기기

[ 프로그래머스 ] 정수 내림차순으로 배치하기 ( java ) 본문

CS/알고리즘 풀이

[ 프로그래머스 ] 정수 내림차순으로 배치하기 ( java )

notEmpty 2019. 12. 8. 22:46

[ 프로그래머스 ] 정수 내림차순으로 배치하기 ( 자바 ) 

n이 118372면 873211을 리턴하기 

n은 8000000000이하 숫자 

 

 

https://programmers.co.kr/learn/courses/30/lessons/12933

 

코딩테스트 연습 - 정수 내림차순으로 배치하기 | 프로그래머스

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

programmers.co.kr

 

구조 1

  1. int타입 배열 생성, 크기는 Math.log10사용 

  2. %, / 를 이용해 (-1 x 값)배열채우기 

  3. 소팅

  4. -1 처리 후 답 생성

 

 

구조 2

  1. char타입 배열 생성. toCharArray

  2. 소팅 

  3. 거꾸로 답 생성 

 

 

추가적으로 더 궁금한 점 있으면 댓글 달아주세요

 

 

 

코드 1 

숫자 그대로 이용해서 답 계산

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
class Solution {
  public long solution(long n) {
        long[] arr = new long[(int)Math.log10(n)+1];
 
        int i = 0;
        long div = 10;
        while(n!=0) {
            arr[i++= -n%div;
            n /= 10;
        }
        Arrays.sort(arr);
 
        long ans = 0;
        for(i = 0 ; i < arr.length ;i++ ) {
            ans += -arr[i];
            ans *= 10;
        }
        System.out.println(ans/10);
      return ans/10;
  }
}
cs

 

코드 2

char로 변환해서 답 계산 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;
class Solution {
  public long solution(long n) {
        char[] input = Long.toString(n).toCharArray();
        Arrays.sort(input);
        long ans = 0;
        for (int i = input.length-1; i >= 0 ; i--) {
            ans += input[i] - '0';
            ans *= 10;
        }
        System.out.println(ans/10);
        return ans/10;
  }
}
cs