본문 바로가기

알고리즘

백준 - 시리얼 번호(Kotlin)

본 알고리즘 풀이는 Routine Study에서 진행하고 있습니다.

https://github.com/ROUTINE-STUDY/Algorithm

 

저를 포함한 구성원이 대부분 초보이므로, 원하시는분은 언제라도 들어오셔도 좋습니다.

 

GitHub - ROUTINE-STUDY/Algorithm: 초보 알고리즘 스터디 / 누구나 참여 가능

초보 알고리즘 스터디 / 누구나 참여 가능 :runner:. Contribute to ROUTINE-STUDY/Algorithm development by creating an account on GitHub.

github.com

문의는 댓글 바람.

 

문제 출처 :https://www.acmicpc.net/problem/1431

 

[문제 설명]

그냥 정렬 문제

 

[접근 방법]

그냥 정렬 조건에 맞춰 정렬하는 문제입니다.

예전에 정렬 조건을 전부 체크 안해서 엄청 큰 낭패를 본 적이 있는데 이번엔 그 당시 경험을 살려서 간단하게 완료했습니다.

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter

fun main() {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val bw = BufferedWriter(OutputStreamWriter(System.out))
    val cntOfSerial = br.readLine().toInt()
    val listOfSerial = ArrayList<Serial>()

    for (idx in 0 until cntOfSerial) {
        listOfSerial.add(Serial(br.readLine()))
    }

    listOfSerial.sort()
    listOfSerial.forEach {
        bw.write(it.no)
        bw.write("\n")
    }
    bw.flush()
}

class Serial(
    val no: String
) : Comparable<Serial> {
    override fun compareTo(other: Serial): Int {
        if (this.no.length > other.no.length) {
            return 1
        } else if (this.no.length < other.no.length) {
            return -1
        }

        val thisSum = this.no.filter { it in '0'..'9' }.sumOf { it.digitToInt() }
        val otherSum = other.no.filter { it in '0'..'9' }.sumOf { it.digitToInt() }
        if (thisSum > otherSum) {
            return 1
        } else if (thisSum < otherSum) {
            return -1
        }

        return this.no.compareTo(other.no)
    }
}
728x90
반응형