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

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ž๋ฆฟ์ˆ˜ ๋”ํ•˜๊ธฐ Swift

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

๋ฌธ์ œ ์„ค๋ช…

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

์ œํ•œ์‚ฌํ•ญ

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

์ž…์ถœ๋ ฅ ์˜ˆ

N answer
987 24
123 6

ํ’€์ด:์˜ˆ์ „์—๋Š” ์ž๋ฆฟ์ˆ˜๋งˆ๋‹ค 10์œผ๋กœ ๋‚˜๋ˆ ์„œ ๊ตฌํ–ˆ์„ํ…๋ฐ ๊ทธ๋ƒฅ ๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์„œ map์œผ๋กœ ๋‚˜๋ˆˆ ๋‹ค์Œ ์ฐจ๋ก€๋กœ ๋”ํ•˜๋ฉด ๋˜๊ฒ ๋‹ค ์ƒ๊ฐํ•ด์„œ

์šฐ์„  n์„ String์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ค€ ๋’ค map์„ ํ•ด์„œ String๊ฐ’์œผ๋กœ ์ฐจ๋ก€๋กœ ๋‚˜๋ˆ„์—ˆ๋‹ค. (Character๋กœ ๋„ฃ์„ ์‹œ Int๋กœ ํ˜•๋ณ€ํ™˜์ด ์•ˆ๋จ)

๊ทธ๋Ÿฐ ๋’ค for๋ฌธ์œผ๋กœ ์ฐจ๋ก€๋กœ Int๋กœ ํ˜•๋ณ€ํ™˜์„ ํ•ด์„œ answer๊ฐ’์— ๋”ํ•ด์คฌ๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
import Foundation
 
func solution(_ n:Int-> Int
{
    var answer:Int = 0
    let string = String(n).map{String($0)}
    for number in 0..<string.count{
       answer += Int(string[number])!
    }
    return answer
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด ์ค‘ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ

reduce๋ฅผ ์ด์šฉํ•ด์„œ for๋ฌธ๊ณผ +=๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์“ธ ์ˆ˜ ์žˆ์Œ.

1
2
3
4
5
6
7
import Foundation
 
func solution(_ n:Int-> Int
{
    return String(n).reduce(0, {$0+Int(String($1))!});
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€