โจ๏ธ Language/swift
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ์ง์๋ ์ซ์ด์
hyebin (Helia)
2022. 11. 30. 12:44
๋ฐ์ํ
ํ๋ก๊ทธ๋๋จธ์ค LV.0 ๋ชจ์
์ง์๋ ์ซ์ด์
๋ฌธ์ ์ค๋ช
์ ์ n์ด ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, n ์ดํ์ ํ์๊ฐ ์ค๋ฆ์ฐจ์์ผ๋ก ๋ด๊ธด ๋ฐฐ์ด์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
- 1 ≤ n ≤ 100
์ ์ถ๋ ฅ ์
n | result |
10 | [1, 3, 5, 7, 9] |
15 | [1, 3, 5, 7, 9, 11, 13, 15] |
์ ์ถ๋ ฅ ์ ์ค๋ช
์ ์ถ๋ ฅ ์ #1
- 10 ์ดํ์ ํ์๊ฐ ๋ด๊ธด ๋ฐฐ์ด [1, 3, 5, 7, 9]๋ฅผ returnํฉ๋๋ค.
์ ์ถ๋ ฅ ์ #2
- 15 ์ดํ์ ํ์๊ฐ ๋ด๊ธด ๋ฐฐ์ด [1, 3, 5, 7, 9, 11, 13, 15]๋ฅผ return ํฉ๋๋ค.
์ ์ถ
import Foundation
func solution(_ n:Int) -> [Int] {
var answer = [Int]()
for i in stride(from: 1, through: n, by: 2) {answer.append(i)}
return answer
}
i๋ฅผ 1๋ถํฐ n๊น์ง 2์ฉ ์ฆ๊ฐ์์ผ ๋ฐฐ์ด์ ์ ์ฅํ ํ ๋ฐํํ๋ค.
๋ค๋ฅธ ํ์ด
func solution(_ n: Int) -> [Int] { (0...n).filter { $0 % 2 == 1 } }
filter ํจ์๋ฅผ ์ฌ์ฉํ์ฌ 0๋ถํฐ n๊น์ง 2๋ก ๋๋์์ ๋ ๋๋จธ์ง๊ฐ 1์ธ ๊ฐ์ ๋ฐํํ๋ค.
๋ฐ์ํ