๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

๋‘ ์ •์ˆ˜ a, b๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ a์™€ b ์‚ฌ์ด์— ์†ํ•œ ๋ชจ๋“  ์ •์ˆ˜์˜ ํ•ฉ์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”.
์˜ˆ๋ฅผ ๋“ค์–ด a = 3, b = 5์ธ ๊ฒฝ์šฐ, 3 + 4 + 5 = 12์ด๋ฏ€๋กœ 12๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

 

์ œํ•œ ์กฐ๊ฑด
  • a์™€ b๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ๋‘˜ ์ค‘ ์•„๋ฌด ์ˆ˜๋‚˜ ๋ฆฌํ„ดํ•˜์„ธ์š”.
  • a์™€ b๋Š” -10,000,000 ์ด์ƒ 10,000,000 ์ดํ•˜์ธ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.
  • a์™€ b์˜ ๋Œ€์†Œ๊ด€๊ณ„๋Š” ์ •ํ•ด์ ธ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
a b return
3 5 12
3 3 3
5 3 12

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ a:Int, _ b:Int) -> Int64 {
    let largeN : Int
    let smallN : Int
    var result = 0
    
    if a > b {
        largeN = a
        smallN = b
    }
    else if b > a {
        largeN = b
        smallN = a
    }
    else {
        return Int64(a)
    }
    
    for i in smallN...largeN {
        result += i
    }
    
    return Int64(result)
}
  • ์ž…๋ ฅ ๋ฐ›์€ ๋‘ ์ˆ˜์ค‘ ๋” ํฐ ์ˆ˜์™€ ์ž‘์€ ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•ด์ฃผ์—ˆ๊ณ , ๋‘ ์ˆ˜๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ๋ฐ”๋กœ a๋ฅผ ์ถœ๋ ฅ, ๊ฐ™์ง€ ์•Š์„ ๋•Œ๋Š” ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ž‘์€ ์ˆ˜๋ถ€ํ„ฐ ํฐ ์ˆ˜๊นŒ์ง€ ๋ˆ„์ ํ•˜์—ฌ ์ถœ๋ ฅํ•ด์ฃผ์—ˆ๋‹ค.

 

์ธ์ƒ์ ์ธ ํ’€์ด
func solution(_ a:Int, _ b:Int) -> Int64 {
    return Array((a < b) ? a...b : b...a).reduce(0, +)
}
  • Array, reduce ์ด์šฉํ•ด์„œ ํ‘ผ ํ’€์ด๋ฅผ ๋ฐœ๊ฒฌํ–ˆ๋‹ค,,! ์™„์ „ ๊น”๋”ํ•˜๋‹ค,,
  • ๊ทผ๋ฐ ๋ง‰์ƒ ๋Œ๋ ค๋ณด๋‹ˆ๊นŒ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ ์ž”๋œฉ,,ใ…œ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ด์„œ ํ•œ๋‹ค๋Š” ๊ฒƒ ์ž์ฒด๊ฐ€ ์‹œ๊ฐ„์„ ๋„ˆ๋ฌด ๋งŽ์ด ์žก์•„๋จน๋Š” ๋“ฏ ํ•˜๋‹ค.
  • ๊ทธ๋ž˜๋„ Array ์‚ฌ์šฉํ•ด์„œ ๋งŒ๋“  ์‹์ด ๋ฐฐ์šธ ์ ์ด ๋งŽ์€ ๊ฒƒ ๊ฐ™์•„ ๊ฐ€์ ธ์™€๋ดค๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฝ”๋“œ๊ฐ€ ์กฐ๊ธˆ ๊ฐ„๊ฒฐํ•˜์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์•„์„œ,, ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ด์•ผ๊ฒ ๋‹ค.!

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ a:Int, _ b:Int) -> Int64 {
    var result = 0
    
    if a > b {
        for i in b...a {
            result += i
        }
    }
    
    else {
        for i in a...b {
            result += i
        }
    }
    
    return Int64(result)
}
  • a > b์ผ ๊ฒฝ์šฐ, ๋ฐ˜๋Œ€์ผ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ ๊ณ„์‚ฐํ•ด์คฌ๊ณ , for๋ฌธ์œผ๋กœ ๋ˆ„์ ํ•œ ๊ฐ’์„ ๊ตฌํ•ด์คฌ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ ํ’€์ด๋ณด๋‹ค ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ณ  ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ๋„ ์ข‹์€ ๋“ฏ ํ•˜๋‹ค!

 


 

โž•๐Ÿ– [ ๋˜! ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋˜ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ a:Int, _ b:Int) -> Int64 {
    var sum = 0
    for i in (a > b ? b...a : a...b) { sum += i }
    return Int64(sum)
}
  • ์ง„์งœ 200๋ฐฐ ๊น”๋”ํ•ด์กŒ๋‹ค..ใ…œ ๊ฐ๊ฒฉ
  • for๋ฌธ์—์„œ ๋ฒ”์œ„๋กœ ์กฐ๊ฑด์‹์„ ์ ์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜ค๋Š˜ ์•Œ๊ฒŒ ๋˜์–ด์„œ,, ํ•œ๋ฒˆ ํ™œ์šฉํ•ด๋ดค๋‹ค.!

 


 

 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12912

๋Œ“๊ธ€