miniworld

[Swift] 프로그래머스 Lv0. 짝수의 합, for문 stride 본문

Swift/프로그래머스 코딩테스트 연습

[Swift] 프로그래머스 Lv0. 짝수의 합, for문 stride

Dev_miniworld 2024. 1. 12. 16:26

문제 설명

정수 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에 들어가는 값을 포함합니다.

 

필요에 따라 구별해서 사용하면 좋을 것 같습니다.