[Kotlin] ๋ถ€์กฑํ•œ ๊ธˆ์•ก ๊ณ„์‚ฐํ•˜๊ธฐ (ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์•Œ๊ณ ๋ฆฌ์ฆ˜)
๋ฐ˜์‘ํ˜•

 

 

 

 

 

๋ฌธ์ œ

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

 

 

 


 

์ ‘๊ทผ

 

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        
        var fullPrice = 0L
        for (i in 1..count){
            fullPrice += (i * price)
            }
        //1. ์ด ๊ธˆ์•ก์„ ๊ตฌํ•œ๋‹ค.
        
        if(fullPrice > money) return (fullPrice-money).toLong()
        else return 0L
        
         //2. ํ˜„์žฌ ์ž์‹ ์˜ ๊ธˆ์•ก๊ณผ ๋น„๊ตํ•ด์„œ ์–ผ๋งˆ๊ฐ€ ๋ชจ์ž๋ผ๋Š”์ง€๋ฅผ return ํ•œ๋‹ค.
         //3. ๋ชจ์ž๋ผ์ง€ ์•Š์€ ๊ฒฝ์šฐ 0์„ return ํ•œ๋‹ค.
        }
        
    }
}
  • ํ•„์š”ํ•œ ์ด ๊ธˆ์•ก์„ ๊ตฌํ•˜๊ณ , ํ˜„์žฌ ๊ฐ€์ง„ ๊ธˆ์•ก๊ณผ ๋น„๊ตํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌ์ƒํ–ˆ๋‹ค.
  • ๊ทธ๋Ÿฌ๋‚˜ '/Solution.kt:18:1: error: expecting a top level declaration' ์—๋Ÿฌ๊ฐ€ ๊ณ„์† ๋–ด๋‹ค.
  • ์•Œ๊ณ ๋ณด๋‹ˆ ๋ณ„ ๋ฌธ์ œ๋Š” ์•„๋‹ˆ๊ณ , ๋ฐ‘์— }๋ฅผ ํ•˜๋‚˜ ๋” ์ถ”๊ฐ€ํ•ด๋ฒ„๋ฆฐ ๋ฌธ์ œ์˜€๋‹ค.

 

 


 

์„ฑ๊ณต ์ฝ”๋“œ

 

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

 


 

์„ค๋ช…

 

  1. fullPrice๋ผ๋Š” Longํ˜• ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•œ๋‹ค.
  2. 1๋ถ€ํ„ฐ ์ „์ฒด ๊ฐœ์ˆ˜๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉฐ ๊ธˆ์•ก์„ fullPrice์— ๊ณ„์† ๋”ํ•ด์ค€๋‹ค.
  3. ๊ตฌํ•ด์ง„ ์ด ๊ธˆ์•ก(fullPrice)๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” money๋ณด๋‹ค ํฌ๊ณ  ์ž‘์Œ์— ๋”ฐ๋ผ return๊ฐ’์„ ๋ถ„๋ฆฌํ•œ๋‹ค.

 


 

๋‹ค๋ฅธ ๋ฐฉ๋ฒ•

 

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 ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ count์— ๋งž๋Š” ๊ธˆ์•ก์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์ปฌ๋ ‰์…˜์„ ๋งŒ๋“ค๊ณ  sum()์œผ๋กœ ๋”ํ•œ๋‹ค.
  • let๊ณผ it์„ ์ด์šฉํ•ด ๋”ํ•ด์ง„ ๊ธˆ์•ก์— ๋”ฐ๋ผ ๊ฒฐ๊ณผ๋ฅผ ๋ถ„๊ธฐํ•œ๋‹ค.

 

 

 

 

 

 

 

 

๋ฐ˜์‘ํ˜•
 ๐Ÿ’ฌ C O M M E N T