ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Codewars] 7kyu Descending Order (JAVA)
    IT/개발 기록 2019. 1. 16. 12:30

    문제


    Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.


    예제


    Input: 21445 Output: 54421
    Input: 145263 Output: 654321
    Input: 1254859723 Output: 9875543221


    코드1


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static int sortDesc(final int num) {
        ArrayList<String> sort = new ArrayList<String>();
     
        String str = Integer.toString(num);
        String out = "";
        
        for(int i =0; i<str.length(); i++){
         sort.add(str.charAt(i)+"");
        }
     
        Collections.sort(sort);
        Collections.reverse(sort);
     
        for(int i=0; i<sort.size(); i++){
         out += sort.get(i);
        }
     
        System.out.println(Integer.parseInt(out));
    }
     
    cs
     
     
     

    코드2


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public static int sortDesc(final int num) {
        String[] numbers = (Integer.toString(num)).split("");
        Arrays.sort(numbers);
     
        String result = "";
     
        for(String s : numbers)
        {
        result = s + result;
        }
        System.out.println(Integer.parseInt(result));
    }
    cs
     

     

    생각해 볼 부분


     이번 문제를 접근할 때 어려운 문제는 아니기 때문에 로직이 바로 생각이 났다.

    로직은 바로 생각이 났지만 문제는 그 로직을 구현하는 방법이다..

    codewars사이트에서 직접 코드를 입력하고 제출을 하려고 했었는데

    자동완성 기능을 제공하지 않아 제대로 전부를 입력하지 않으면 안된다...

    평소에 필요한 api를 자동완성 기능을 이용해 사용하고 있었기 때문에 굉장히 적응이 안되었다..

    알고리즘 문제를 더 효과적으로 풀기 위해서 기본적인 래퍼런스는 제대로 숙지해야겠다.

     

    먼저 코드1은 내가 푼 방법으로 ArrayList를 사용하고 for문을 두 번 사용했다.

    코드2는 ArrayList가 아닌 배열을 사용하고 한번의 for문을 사용했다.

    arraylist와 배열의 성능차이는 위 문제에서 크게 알 수 없지만

    for문을 두번사용했다라는건 큰 성능차이이다.

     

    기본적인 래퍼런스 사용법 숙지! 꼭 하도록하자!

     

     

     





    댓글