๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

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

by Fomagran ๐Ÿ’ป 2020. 2. 11.
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์„ค๋ช…

๋‘ ์ •์ˆ˜ 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

๋‚˜์˜ ํ’€์ด: a๊ฐ€ b๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ์™€ a๊ฐ€ b๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ a์™€ b๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ ์ด๋ ‡๊ฒŒ 3๊ฐ€์ง€๋กœ ๋‚˜๋ˆด๋‹ค.

๊ทธ๋ฆฌ๊ณค var sum์œผ๋กœ ํ•ฉ์„ ๋งŒ๋“ค์–ด์ฃผ๊ณ  a,b๊ฐ’์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์—†๊ธฐ์— ๊ฐ ๊ฐ newa,newb๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ณ  ํ•ฉ์—๋‹ค๊ฐ€ ๋”ํ•ด์ค€ ๋’ค

a,b์‚ฌ์ด๋งŒํผ 1์”ฉ ๋”ํ•ด์คฌ๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Foundation
func solution(_ a:Int, _ b:Int-> Int64 {
    var sum = 0
    var newa = a
    var newb = b
    if a > b {
        for _ in 0...a-b{
        sum += newb
        newb += 1
        }
        return Int64(sum)
    } else if a < b{
        for _ in 0...b-a{
      sum += newa
       newa += 1
        }
        return Int64(sum)
 
    } else{
        return Int64(a)
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด ์ค‘ ๊ฐ€์žฅ ์ข‹์€ ํ’€์ด

ํ’€์ด ์กฐ๊ฑด ? a:b๋ฅผ ํ†ตํ•ด ๊ฐ’ ์ถ”์ถœ

Array(a...b)๋ฅผ ์ด์šฉํ•ด ํ•œ๋ฒˆ์— a๋ถ€ํ„ฐb๊นŒ์ง€์˜ ๊ฐ’์„ ๋„ฃ์–ด๋ฒ„๋ฆฌ๊ณ 

reduce๋ฅผ ์ด์šฉํ•ด 0๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ๋”ํ•ด๋ฒ„๋ฆผ

1
2
3
4
func solution(_ a:Int, _ b:Int-> Int64 {
    return Int64(Array(a > b ? b...a : a...b).reduce(0+))
  }
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€