ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준] 1001번 : A-B - 코틀린(Kotlin)
    카테고리 없음 2022. 10. 19. 00:01
    728x90

    https://www.acmicpc.net/problem/1001

     

    1001번: A-B

    두 정수 A와 B를 입력받은 다음, A-B를 출력하는 프로그램을 작성하시오.

    www.acmicpc.net

     

    문제 해석

    두 정수 A와 B를 입력받은 다음, A-B의 결과를 출력하는 간단한 프로그램입니다.

     

    문제 풀이 전 설계

    Kotlin에서 입력받는 방법을 알아보고 split을 통해 A와 B를 구분합니다.

     

    코드

    fun main() {
        val input : String = readLine() ?: throw IllegalStateException()
        val split = input.split(" ")
        val a = split[0].toInt()
        val b = split[1].toInt()
        println(a-b)
    }

    readLine을 활용하여 구현하였습니다.

     

    이렇게도 쓸 수 있는데 가독성이 딱히 좋은지는 잘 모르겠습니다.

    fun main() {
        val input: String = readLine() ?: throw IllegalStateException()
        with(input.split(" ")) {
            println(get(0).toInt() - get(1).toInt())
        }
    }

     

    다른분들의 코드를 통해 배운 점

     

    비슷한 방식으로 이렇게도 구현할 수 있다는 것을 알게 되었습니다.

    fun main() = print(readLine()?.let { it[0] - it[2] })

    let을 활용하여  null처리를 하는 방식입니다.

     

    하지만 이는 0~9 사이의 숫자에만 해당하며 조금 더 확장적인 방법은 다음과 같습니다.

    fun main()=print(readLine()?.split(" ")?.let{ it[0].toInt()-it[1].toInt()})

    가끔 예제에  readln을 활용한 방식이 보이는데 kotlin 1.6 이후부터 null처리를 지원하는 메서드 같습니다.

    public actual fun readln(): String = readlnOrNull() ?: throw ReadAfterEOFException("EOF has already been reached")

     

     

    가장 짧은 시간으로는 BufferedReader와 StringTokenizer를 활용한 방법이 있습니다.

     

    또한 간단한 코드로는 Scanner를 활용한 코드도 있습니다.

    import java.util.*
    fun main() {
        val input = Scanner(System.`in`)
        var iA: Int = input.nextInt()
        var iB: Int = input.nextInt()
        println(iA-iB)
    }

     

    이를 with를 활용하여 조금 더 코틀린스럽게 한다면 다음과 같이 쓸 수 있습니다.

    import java.util.*
    
    fun main(args: Array<String>) = with(Scanner(System.`in`)){
        println(nextInt() - nextInt())
    }

     

     

     

     

    출처

    https://github.com/JetBrains/kotlin/blob/ea836fd46a1fef07d77c96f9d7e8d7807f793453/libraries/stdlib/jvm/src/kotlin/io/Console.kt#L152

     

    GitHub - JetBrains/kotlin: The Kotlin Programming Language.

    The Kotlin Programming Language. . Contribute to JetBrains/kotlin development by creating an account on GitHub.

    github.com

     

    댓글

Designed by Tistory.