코딩테스트

프로그래머스 | 부족한 금액 계산하기 | Kotlin

다시은 2024. 1. 6. 09:43

 

 

내 풀이

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        var answer: Long = 0
        var total: Long = 0
        for(i in 1..count) {
            total += (i * price)
        }
        if ( money - total < 0) answer = total - money else answer = 0 
        return answer
    }
}

이용 횟수가 늘어갈 수록 price가 배로 늘어나는 걸 그냥 for 문에 넣었다....만능 for문...

 

 

 

다른 사람 풀이

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long
= (1..count).map { it * price.toLong() }.sum().let { if (money > it) 0 else it - money }
}

map 넣어서 해볼까말까 하다가 안했는데 주말이라고 대충하고싶은 속마음이 있었나바....다시 나 혼자 해봤다.

long과 int 를 연산하면 자동으로 타입 변환이 돼서 long 타입으로 나온다.

처음 price.toLong()를 곱할 때 long 으로 결괏값이 나오고 그 뒤로도 쭉쭉 long 타입

 

 

 

 

 

다른 사람 풀이 2

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        val answer: Long = money-((count*(count+1))/2).toLong()*price.toLong()
        return if(answer>0)0 else -1*answer
    }
}

(count*(count+1)/2)*price)가 계산 되는건 알겠는데

총 이용금액을 한번에 이렇게 구하라고 하면 난 전혀 못하겠다.

 

최종 이용금액 = price * (1 + 2 + 3 + ...count)

(1 + 2 + .. n ) = ( n * ( n+1 )) / 2

 

최종 이용금액 = (n*(n+1)) / 2 * price

 

학생 때 본 기억은 있다 😂😂😂