๐ Problem Solution/Programmers
ํ๋ก๊ทธ๋๋จธ์ค ์ฝ์์ ํฉ Swift
Fomagran ๐ป
2020. 2. 23. 18:57
728x90
๋ฐ์ํ
๋ฌธ์ ์ค๋ช
์ ์ n์ ์ ๋ ฅ๋ฐ์ n์ ์ฝ์๋ฅผ ๋ชจ๋ ๋ํ ๊ฐ์ ๋ฆฌํดํ๋ ํจ์, solution์ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
- n์ 0 ์ด์ 3000์ดํ์ธ ์ ์์ ๋๋ค.
์ ์ถ๋ ฅ ์
n | return |
5 | 6 |
12 | 28 |
ํ์ด:๊ฑ 0์ผ ๋๋ง ์กฐ์ฌํ๊ณ ๋๋จธ์ง๋ for๋ฌธ ๋๋ ค์ ๋๋์ด ๋จ์ด์ง๋ ๊ฒ๋ค์ ๋ํด์ฃผ๋ฉด ๋จ.
1
2
3
4
5
6
7
8
9
|
func solution(_ n:Int) -> Int {
var count = 0
for i in 1...n{
if n%i == 0 {
count += i
}
}
return n == 0 ? 0 :count
}
|
๋ค๋ฅธ ์ฌ๋ ํ์ด ์ค ๊ฐ์ฅ ์ข๋ค๊ณ ์๊ฐํ๋ ๊ฒ
์ฐ์ guard๋ฌธ์ ์ด์ฉํด 0์ผ ๊ฒฝ์ฐ๋ฅผ ๋๋นํ๊ณ
Array์ filter๋ฅผ ์ด์ฉํด ๋๋์ด ๋จ์ด์ง๋ ๊ฒ์ ๋ฃ๊ณ reduce๋ฅผ ์ด์ฉํด์ ์ฐจ๋ก๋ก ๋ํ๋ค.
๋๋ reduce๋ฅผ ์๊ฐํ๋๋ฐ ๋์ถฉ ๋จธ๋ฆฌ์ฐ๊ธฐ ๊ท์ฐฎ์์ for๋ฌธ์ ๋๋ ธ๋ค.
1
2
3
4
5
6
|
func solution(_ n:Int) -> Int {
guard n != 0 else {
return 0
}
return Array(1...n).filter{n % $0 == 0}.reduce(0, +)
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
728x90
๋ฐ์ํ