Kotlin Day 2 사칙연산, 조건문, 배열

cozzin·2023년 4월 10일
0

프로그래머스 코딩테스트 입문 따라하면서 코틀린 익히는 중 입니다.
https://school.programmers.co.kr/learn/challenges/beginner?order=acceptance_desc

두 수의 나눗셈

처음에는 이렇게 작성했는데

class Solution {
    fun solution(num1: Int, num2: Int): Int {
        val divided = num1.toDouble() / num2.toDouble()
        return (divided * 1000).toInt()
    }
}

더 나은 답을 발견

class Solution {
    fun solution(num1: Int, num2: Int) = num1 * 1000 / num2
}
  • 1000을 미리 곱하면 자릿수가 버려지는 것을 고민하지 않아도 됨
  • 함수를 길게 작성하지 않고 선언적으로 식을 표현함

두 수의 비교

https://school.programmers.co.kr/learn/courses/30/lessons/120807?language=kotlin

삼항연산자를 써야겠다고 생각했다.

class Solution {
    fun solution(num1: Int, num2: Int): Int = num1 == num2 ? 1 : -1
}

이렇게 하면 안된다. 코틀린에서는 삼항연산자가 없다.

In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator (condition ? then : else) because ordinary if works fine in this role.
https://kotlinlang.org/docs/control-flow.html#if-expression

대신 if이 expression이라서 결과값을 반환할 수 있다고 한다.

class Solution {
    fun solution(num1: Int, num2: Int): Int = if (num1 == num2) 1 else -1
}

분수의 덧셈

https://school.programmers.co.kr/learn/courses/30/lessons/120808

첫 번째 분수의 분자와 분모를 뜻하는 numer1, denom1, 두 번째 분수의 분자와 분모를 뜻하는 numer2, denom2가 매개변수로 주어집니다. 두 분수를 더한 값을 기약 분수로 나타냈을 때 분자와 분모를 순서대로 담은 배열을 return 하도록 solution 함수를 완성해보세요.

문제를 해결하기 위해서 최대공약수가 필요하다.
https://blockdmask.tistory.com/53

class Solution {
    fun solution(numer1: Int, denom1: Int, numer2: Int, denom2: Int): IntArray {
        val sumNumer = numer1 * denom2 + numer2 * denom1
        val sumDenom = denom1 * denom2
        val greatestCommonDivisor = greatestCommonDivisor(sumNumer, sumDenom)

        val resultNumer = sumNumer / greatestCommonDivisor
        val resultDenom = sumDenom / greatestCommonDivisor

        var answer: IntArray = intArrayOf(resultNumer, resultDenom)
        return answer
    }

    private fun greatestCommonDivisor(a: Int, b: Int): Int {
        return if (b == 0) {
            a
        } else {
            greatestCommonDivisor(b, a % b)
        }
    }
}

배열 두배 만들기

https://school.programmers.co.kr/learn/courses/30/lessons/120809

map을 쓰면 간단히 해결된다. 그런데 map을 쓰면 List로 나오는 모양이다.

class Solution {
    fun solution(numbers: IntArray): IntArray {
        return numbers.map { it * 2 }.toIntArray()
    }
}
profile
Software Engineer

0개의 댓글