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

[Swift Algorithm] ์ž๋ฆฟ์ˆ˜ ๋”ํ•˜๊ธฐ Programmers(Lv.1)

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

์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์ง€๋ฉด, N์˜ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ์„ ๊ตฌํ•ด์„œ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ์„ธ์š”.
์˜ˆ๋ฅผ๋“ค์–ด N = 123์ด๋ฉด 1 + 2 + 3 = 6์„ return ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

์ œํ•œ ์กฐ๊ฑด
  • N์˜ ๋ฒ”์œ„ : 100,000,000 ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜

 

์ž…์ถœ๋ ฅ ์˜ˆ
N answer
123 6
987 24

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution1(_ n:Int) -> Int
{
    var answer:Int = 0
    answer = String(n).map{Int(String($0))!}.reduce(0, +)

    return answer
}
  • String์œผ๋กœ ์บ์ŠคํŒ… ํ•œ ํ›„, String ์š”์†Œ ๊ฐ’๋“ค์„ ๋ชจ๋‘ Int๋กœ ์บ์ŠคํŒ…, reduce๋กœ ๋ชจ๋“  ๊ฐ’์„ ๋”ํ•ด์ฃผ์—ˆ์Œ

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • map, reduce ์ด์šฉํ•˜๋ฉด ๋ฐ”๋กœ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€์Œ

 


 

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

func solution2(_ n:Int) -> Int {
    return String(n).map{ Int(String($0))! }.reduce(0, +)
}
  • ์ฒซ ๋ฒˆ์งธ ํ’€์ด์™€ ๋กœ์ง์€ ๊ฐ™์ง€๋งŒ, ๊ตณ์ด ์ƒ์ˆ˜๋ฅผ ๋”ฐ๋กœ ์„ ์–ธํ•˜์ง€ ์•Š๊ณ  ํ•œ ์ค„๋กœ ํ‘œํ˜„ํ•˜์—ฌ ๊ฐ„๊ฒฐํ•ด์กŒ์Œ

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€