Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- randomElement
- 대소문자바꾸기
- swift grammer
- 랜덤추출
- 코딩테스트
- Swift문법
- Swift
- Property Observer
- lifecycle
- willset
- 짝수의합
- 야곰아카데미
- @main
- 프로그래머스
- Stride
- @State
- IOS
- LV0
- 생명주기
- didset
- Swift 문법
- @Binding
- dismiss
- App구조
- inout
- navigationcontroller
- SwiftUI
- 공식문서
- propertWrappers
- 문자열 반복
Archives
- Today
- Total
miniworld
[Swift] 프로그래머스 Lv0. 짝수의 합, for문 stride 본문
문제 설명
정수 n이 주어질 때, n 이하의 짝수를 모두 더한 값을 return 하도록 solution 함수를 작성해주세요.
입출력 예
n | result |
10 | 30 |
4 | 6 |
내 풀이
import Foundation
func solution(_ n:Int) -> Int {
var result = 0
for i in stride(from: 0, to: n+1, by: 2) {
result += i
}
return result
}
for 문의 stride을 통해서 구현을 했는데요.
stride의 사용법을 한번 알아볼까요?
stride(from: , to: , by: )
stride(from: , through: , by: )
stride는 다음과 같이 두가지가 있습니다.
두 개의 차이점을 살펴보기 위해 예제를 한번 살펴볼까요?
import Foundation
for i in stride(from: 0, to: 10, by: 2) {
print("stride(to): \(i)")
}
for i in stride(from: 0, through: 10, by: 2) {
print("stride(through): \(i)")
}
예제 코드의 결과는 다음과 같습니다!!
stride(from: , to: , by: ) 는 to에 들어가는 값을 포함하지 않고,
stride(from: , through: , by: ) 는 through에 들어가는 값을 포함합니다.
필요에 따라 구별해서 사용하면 좋을 것 같습니다.
'Swift > 프로그래머스 코딩테스트 연습' 카테고리의 다른 글
[Swift] 프로그래머스 Lv0. 공백으로 구분하기1 / split() 과 components() 구분! (0) | 2024.01.17 |
---|---|
[Swift] 프로그래머스 Lv0. 대소문자 바꿔서 출력하기 (0) | 2023.07.12 |
[Swift] 프로그래머스 Lv0. 문자 반복 출력하기 (0) | 2023.07.10 |