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

0

프로그래머스

목록 보기
75/127
post-thumbnail

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

풀이

import java.util.*

class Solution {
    fun solution(n: Long): Long {
        //ex.n = 118372
        val nMutableList: MutableList<Long> = mutableListOf()
        var num:Long = n
        while(num > 0){
            nMutableList.add(num%10) //add to end of array
            num /= 10
        }
        //nMutableList={2,7,3,8,1,1}
        
        nMutableList.sort()
        //nMutableList={1,1,2,3,7,8}
        
        var answer: Long = 0
        var digit:Int = 1
        for(digitNum in nMutableList){
            answer += (digitNum*digit)
            digit*=10
        }
        //answer=(1*1)+(1*10)+(2*100)+...+(8*100000)=873211
        return answer
    }
}

참고자료

📌Kotlin sort 정렬 오름차순, 내림차순, 임의 순

Immutable 리스트 정렬

  • sorted(): 오름차순 정렬된 List 생성하여 반환
  • reversed(): 역순으로 정렬된 List 생성하여 반환
  • sorted().reversed(): 내림차순 정렬된 List 생성하여 반환

Mutable 리스트 정렬

  • sort(): 리스트 자신을 오름차순 정렬
  • reverse(): 리스트 자신을 역순으로 정렬
  • sort().reverse(): 리스트 자신을 내림차순으로 정렬
  • sortDescending(): 리스트 자신을 내림차순 정렬

sortedBy/sortBy

  • 리스트의 요소가 여러 객체를 갖고 있는 타입일 때, 어떤 객체를 비교하여 정렬할 지 결정
  • Immutable 리스트 정렬: sortedBy()
  • Mutable 리스트 정렬: sortBy()
//infix fun <A, B> A.to(that: B): Pair<A, B>
val tupleMutableList = mutableListOf("d" to 4, "a" to 10, "c" to 8, "h" to 5)
println(tupleMutableList)
//[(d, 4), (a, 10), (c, 8), (h, 5)]

tupleMutableList.sortBy { it.first }
println(tupleMutableList)
//[(a, 10), (c, 8), (d, 4), (h, 5)]

tupleMutableList.sortBy { it.second }
println(tupleMutableList)
//[(d, 4), (h, 5), (c, 8), (a, 10)]

sortedWith/sortWith (Comparator 구현하여 정렬)

  • Immutable 리스트 정렬: sortedWith()
  • Mutable 리스트 정렬: sortWith()
  • Comparator 직접 구현하여 sortedWith()/sortWith()의 인자로 전달
  • Comparator 구현 방법: compareBy의 Lamda에 비교할 객체 리턴되도록 만들기
//immutable 리스트
val list = listOf("apple", "banana", "kiwi")

//Comparator 직접 구현 예
val comparator : Comparator<String> = compareBy {it.length}

val lengthOrderList = list.sortedWith(comparator)
println(${lengthOrderList})
//[kiwi, apple, banana]
//Mutable 리스트
val dateMutableList = mutableListOf(
    Date(2020,4,3), 
    Date(2021,5,2), 
    Date(2020,3,16)
)
    
//Comparator 직접 구현
val comparator = compareBy<Date> {it.year}.thenBy{it.month}.thenBy{it.day}
    
dateMutableList.sortWith(comparator)
println(dateMutableList)
//[Fri Apr 16 00:00:00 UTC 3920, Mon May 03 00:00:00 UTC 3920, Thu Jun 02 00:00:00 UTC 3921]
profile
Be able to be vulnerable, in search of truth

0개의 댓글