ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ–ฅ ๋ฌธ์ œ

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

๐Ÿค” ํ’€์ด ๋ฐฉ๋ฒ•

for๋ฌธ์œผ๋กœ ๊ตฌํ˜„

  1. String(n)
    • Int ํ˜•์‹์œผ๋กœ ๋˜์–ด์žˆ๋Š” n์„ String์œผ๋กœ ๋ฐ”๊พธ์–ด์ค€๋‹ค.
  2. answer += Int(String(strN))!
    • strN์„ ํ•œ๊ธ€์ž์”ฉ Int ํ˜•์‹์œผ๋กœ ๋ฐ”๊พธ์–ด์ฃผ๋ฉฐ ๋”ํ•ด์ค€๋‹ค.

map์œผ๋กœ ๊ตฌํ˜„

  1. String(n)
    • Int ํ˜•์‹์œผ๋กœ ๋˜์–ด์žˆ๋Š” n์„ String์œผ๋กœ ๋ฐ”๊พธ์–ด์ค€๋‹ค.
  2. .map{Int(String($0))!} : map์„ ์ด์šฉํ•˜์—ฌ n์„ [Int] ํ˜•์‹์œผ๋กœ ๋ฐ”๊พธ์–ด์ค€๋‹ค.
    • $0 : [String.Element]
    • String($0) : String
    • Int(String($0))! : [Int]
  3. .reduce(0, +)
    • [Int] ๋ฐฐ์—ด ์•ˆ์˜ ์ˆซ์ž๋ฅผ ๊ฐ๊ฐ ๊บผ๋‚ด์–ด + ์—ฐ์‚ฐํ•œ๋‹ค.

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป Swift Code

for๋ฌธ์œผ๋กœ ๊ตฌํ˜„

import Foundation

func solution(_ n:Int) -> Int
{
    var answer:Int = 0

    for strN in String(n) {
        answer += Int(String(strN))!
    }

    return answer
}

map์œผ๋กœ ๊ตฌํ˜„

import Foundation

func solution(_ n:Int) -> Int
{
    var answer:Int = String(n).map{Int(String($0))!}.reduce(0, +)

    return answer
}

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ž๋ฆฟ์ˆ˜ ๋”ํ•˜๊ธฐ

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

programmers.co.kr

 

๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
๊ธ€ ๋ณด๊ด€ํ•จ