๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Kotlin/Programmers Algorithm

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฝ”ํ‹€๋ฆฐ] x๋งŒํผ ๊ฐ„๊ฒฉ์ด ์žˆ๋Š” n๊ฐœ์˜ ์ˆซ์ž #12954

by eun.24k 2023. 10. 21.

#12954

๐ŸŽ„ Question ?

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

class Solution {
    fun solution(x: Int, n: Int): LongArray {
        var answer = longArrayOf()
        return answer
    }
}

๐Ÿงฉ Thought Process

  1. for loop ์„ ์‚ฌ์šฉํ•ด์„œ n๋ฒˆ ๋ฆฌ์ŠคํŠธ์— ์—˜๋ ˆ๋จผํŠธ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
  2. x ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ x์˜ ๋ฐฐ์ˆ˜๊ฐ€ ๋˜๋Š” ์ˆ˜๋“ค์„ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•œ๋‹ค.
// ์˜ค๋Š˜ ๋ฐฐ์šด ๋ฌธ๋ฒ•!
// ๊ทธ๋ƒฅ array๋‚˜ list๋Š” ์ˆ˜์ •์ด ๋ถˆ๊ฐ€ํ•ด์„œ mutableList๋กœ ๋ณ€๊ฒฝํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.

val list: MutableList<Int> = answer.toMutableList()
list.add(element)

//๊ทธ๋ ‡๊ฒŒ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆ˜์ •ํ•ด ์ค€ ํ›„ ๋‹ค์‹œ array๋กœ ๋Œ๋ ค ๋†“์•„์•ผ ๋œ๋‹น.

list.toTypedArray()

 

๐ŸŽ€ Answer

class Solution {
    fun solution(x: Int, n: Int): Array<Int> {
        var answer = intArrayOf()
        val list: MutableList<Int> = answer.toMutableList()
        for (i in 1..n) {
            list.add(x*i)
        }
        
        return list.toTypedArray()
        
    }
}

ํ…Œ์ŠคํŠธ์— ํ†ต๊ณผํ•ด์„œ ์œ„ ๋‹ต์ด ๋งž๋Š”๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๋ฌธ์ œ๋ฅผ ์ œ์ถœํ•˜๋‹ˆ๊นŒ test 13๊ณผ test 14์ด ํ‹€๋ ธ๋‹ค๊ณ  ๋–ด๋‹ค.

ํ…Œ์ŠคํŠธ 13๊ณผ 14์ด ์–ด๋–ค ํ…Œ์ŠคํŠธ์ธ์ง€๋ฅผ ๋ชจ๋ฅด๋‹ˆ๊นŒ ๋ง‰๋ง‰ํ–ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋ฌธ์ œ๋ฅผ ์ฐจ๊ทผํžˆ ๋‹ค์‹œ ์ฝ์–ด๋ณด๋‹ˆ function solution์˜ ์ถœ๋ ฅ๊ฐ’์ด LongArray์˜€๋‹ค. ๊ทธ๋ž˜์„œ ์•„ ํ…Œ์ŠคํŠธ 13 ๊ณผ 14๋Š” ์•„์ฃผ ํฐ ์ˆ˜์—ฌ์„œ Int๋กœ๋Š” ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผ๋ฅผ ๋ชปํ•˜๊ฒ ๊ตฌ๋‚˜ ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค.

 

๊ทธ๋ž˜์„œ ๋ชจ๋‘ Long์œผ๋กœ ๋ฐ”๊พธ์—ˆ๋‹ค. Array<Int> ๋ถ€๋ถ„๋„ Array<Long>์œผ๋กœ ๋ฐ”๊พธ์—ˆ์ง€๋งŒ ์—ฌ์ „ํžˆ ์—๋Ÿฌ๊ฐ€ ๋–ด๋‹ค.

list.toTypedArray๋Š” Array<Long> ํƒ€์ž…์ด๊ณ  ๋‘๋ฒˆ์งธ ์ค„์— ๋‚˜๋Š” LongArray๋ผ๊ณ  ์ ์—ˆ์—ˆ๋‹ค.

๊ทธ๋ž˜์„œ ์œ„์— ์žˆ๋Š” LongArray๋ฅผ Array<Long> ํƒ€์ž…์œผ๋กœ ๋ฐ”๊พธ์–ด์ฃผ๋‹ˆ ๋ฌธ์ œ๊ฐ€ ํ•ด๊ฒฐ๋˜์—ˆ๋‹ค.

class Solution {
    fun solution(x: Int, n: Int): Array<Long> {
        var answer = longArrayOf()
        val list: MutableList<Long> = answer.toMutableList()
        for (i in 1..n) {
            list.add(x*i.toLong())
        }
        return list.toTypedArray()
    }
}

๐ŸŽ Result

 

๐Ÿ† Comment

์ƒ๋‹นํžˆ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค. ๋ฌธ์ œ์—์„œ๋Š” ๋ถ„๋ช…ํžˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฆฌํ„ดํ•ด์•ผ ํ•˜๋Š”๋ฐ ์ดˆ๊ธฐ์— ์ ํ˜€ ์žˆ๋Š” ์ฝ”๋“œ์—๋Š” ๋กฑ์–ด๋ ˆ์ด๊ฐ€ ๋‚˜์™€์žˆ์–ด์„œ ๋ญ์ง€?? ์‹ถ์—ˆ๋Š”๋ฐ ๋ฌธ์ œ์—์„œ ํžŒํŠธ๋ฅผ ์ค€ ๊ฒƒ ๊ฐ™๋‹ค.

 

์–ด๋ ˆ์ด์— ์—˜๋ ˆ๋ฉ˜ํŠธ๋ฅผ ์ถ”๊ฐ€๋กœ ํ• ๋‹นํ•˜๋Š” ๋ฐฉ๋ฒ•์ด mutablelist๋ฅผ ์‚ฌ์šฉํ•œ๋Š” ๋ฐฉ๋ฒ• ๋ง๊ณ ๋„ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ๋” ์žˆ์—ˆ๋‹ค. ๋‚˜์ค‘์— ์‹œ๊ฐ„์ด ๋˜๋ฉด ์ถ”๊ฐ€๋กœ ๊ณต๋ถ€ํ•ด๋ณด๋ฉด ์ข‹๊ฒ ๋‹ค.

 

https://www.techiedelight.com/add-new-element-array-kotlin/