Skip to content

[Kotlin] 조건이 참이면 1, 거짓이면 0을 출력하세요. #10

Description

@dkdud9261

예를 들어 짝수이면 1, 홀수이면 0을 출력하세요의 경우

fun solution(n: Int) = if (n % 2 == 0) 1 else 0

원래 같으면 이런 식으로 했겠지만

fun solution(n: Int) = (n % 2 == 0).compareTo(false)

나처럼 if문 기피증이 있다면 이렇게도 할 수 있다.
나는 코드는 이게 더 예뻐보이는데 가독성 측면에서는 뭐가 나으려나요 🤔

compareTo

fun compareTo(other: Boolean): Int

this가 크면 1, 같으면 0, 작으면 -1을 반환한다.

println(true.compareTo(true)) // 0
println(true.compareTo(false)) // 1
println(false.compareTo(true)) // -1

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions