SW Test/Programmers

[Programmers] Lv2.k์ง„์ˆ˜์—์„œ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 10. 12. 17:57
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

 

 

์˜ˆ์‹œ

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

 

 

 

ํ’€์ด

  • ์†Œ์ˆ˜ ์ฐพ๊ธฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ์ •๋ง ๋งŽ์ด ์žˆ์œผ๋‹ˆ ์ƒ๋žตํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
  • ํ•ด๋‹น ๋ฌธ์ œ์—์„œ๋Š” k์ง„์ˆ˜๋กœ ๋ณ€๊ฒฝ ์‹œ์— Int์˜ ํฌ๊ธฐ ์ž๋ฆฌ์ˆ˜๋ณด๋‹ค๋Š” ์ปค์ง€๊ธฐ ๋•Œ๋ฌธ์— ์†Œ์ˆ˜ ํŒ๋ณ„ํ•จ์ˆ˜์—์„œ๋Š” Long์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
  • StringBuilder์— ํ•˜๋‚˜์”ฉ ๋‚˜๋ˆ ์„œ ์ถ”๊ฐ€ํ–ˆ์ง€๋งŒ, toString(k) ๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฐ”๋กœ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๐Ÿ˜… ์—ญ์‹œ ๋˜ ๋‹ค์‹œ ํ•œ๋ฒˆ ํ•จ์ˆ˜๋ฅผ ๋งŽ์ด ์•Œ์•„์•ผ ๋ชธ์ด ๊ณ ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์„ ๊นจ๋‹ซ๊ฒŒ ๋˜๋„ค์š” .
import kotlin.math.*

class Solution {
    fun isPrime(n: Long): Boolean{
        if(n == 1L) return false
        
        (2..sqrt(n.toDouble()).toLong()).forEach{
            if(n%it == 0L) return false
        }
        return true
    }
    
    
    fun solution(n: Int, k: Int): Int {
        var answer: Int = -1
        
        val str = StringBuilder().apply{
            var num = n
            while(num>0){
                append(num%k)
                num/=k
            }
            reverse()
        }
        
        return str.split("0").filter{it.isNotEmpty()}.filter{isPrime(it.toLong())}.size
    }
}

 

 

 

์ฐธ๊ณ 

  • ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์ธ kotlin์˜ ํŠน์„ฑ์— ๋งž๊ฒŒ ํ•จ์ˆ˜๋ฅผ ๋งŽ์ด ์ตํžˆ์ž ๐Ÿ˜ฝ
  • ์ฐธ๊ณ ๋กœ String์—๋Š” reversed() ๋ฉ”์†Œ๋“œ์ด๊ณ  StringBuilder๋Š” reverse() ์ž…๋‹ˆ๋‹ค~
๋ฐ˜์‘ํ˜•