Focus On Develop ๐ŸคŸ๐ŸคŸ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ ๋ณธ๋ฌธ

iOS [Swift]/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2020. 12. 18. 13:40

<๋ฌธ์ œ>


<์ „๋žต์งœ๊ธฐ>

์‚ฌ์‹ค ์ฃผ์–ด์ง€๋Š” a, b ์‚ฌ์ด์˜ ํ•ฉ์„ for๋ฌธ์œผ๋กœ ๋Œ๋ฆฌ๋ฉด ๋˜๋Š” ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์ธ๋ฐ, ๊ณ ๋ฏผ๋˜๋Š”๊ฑด a์™€ b์˜ ๋Œ€์†Œ๊ด€๊ณ„๋ฅผ ๋น„๊ตํ•˜์ง€ ์•Š๊ณ  ํ•œ๋ฒˆ์— ์ ์šฉ ๊ฐ€๋Šฅํ•œ ๋กœ์ง์ด ์žˆ๋‚˜..? ์Œ.. reduce๋ฅผ ์“ฐ๋ฉด ๋  ๊ฒƒ ๊ฐ™์€๋ฐ Array๋ฅผ ๋ฒ”์œ„๋กœ ์ •์˜ํ•  ์ค„ ๋ชจ๋ฅด๋Š” ํ‘์šฐ์ด๋ฏ€๋กœ.. ์ผ๋‹จ ํ’€๊ณ  ๊ณต๋ถ€ํ•ด์•ผ๊ฒ ๋‹ค ใ…Žใ…Ž ๐Ÿ˜ญ

 

<์ฝ”๋“œ>

func solution(_ a:Int, _ b:Int) -> Int64 {
    var res: Int64 = 0
    if a > b {
        for i in b...a {
            res += Int64(i)
        }
        return res
    } else {
        for i in a...b {
            res += Int64(i)
        }
        return res
    }
}

 

<Lesson Learned>

์ผ๋‹จ ํ†ต๊ณผํ•˜๊ณ  ๋‹ค๋ฅธ์‚ฌ๋žŒ ํ’€์ด ์ฐธ๊ณ ํ•ด๋ณด๊ธฐ ๊ณ ๊ณ ์‹ฑ !!! ์˜ค์˜ค.. Array๋ฅผ ๋ฒ”์œ„๋กœ ์ •์˜ํ•˜๋ ค๋ฉด ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋˜๋Š”๊ตฐ๐Ÿ‘๐Ÿ‘ ์‚ฌ์‹ค ๋‘๋ฒˆ์งธ ์ค„๋กœ ์‹œ๋„ ์•ˆํ•ด๋ณธ๊ฑด ์•„๋‹Œ๋ฐ ์•ˆ๋˜๋”๋ผ ๐Ÿ˜‚ ใ…‹ใ…‹ 

let array = Array(3...5) // Correct
let array = [3...5] // Error

๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด ์ค‘ ๋”ฑ ๋‚ด๊ฐ€ ํ•˜๊ณ  ์‹ถ์—ˆ๋˜ ์ฝ”๋“œ๋ฅผ ์งœ์‹  ๋ถ„์ด ์žˆ์–ด์„œ ๋ฉ”๋ชจํ•ด๋‘ฌ์•ผ๊ฒ ๋‹ค.

func solution(_ a:Int, _ b:Int) -> Int64 {
  return Int64(Array(a > b ? b...a : a...b).reduce(0, +))
}

 

 

์ถœ์ € : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ

Comments