알고리즘/Programmers

[Swift_Programmes] 자릿수 더하기

YEN_ 2023. 11. 20. 10:17

 

 

프로그래머스 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/12931


풀이    

 

import Foundation

func solution(_ n:Int) -> Int
{
    var answer:Int = String(n).reduce (0, { $0 + Int(String($1))! })
    
    return answer
}

중요 개념    

  • 입력받은 자연수가 있다. 각 자릿수의 합을 구하는 문제이다.
    • N = 123이면 1 + 2 + 3 = 6을 return
  • reduce
    • 컨테이너 내부의 값을 하나로 통합하여 더하는 메소드
func reduce<Result>(
    _ initialResult: Result,
    _ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result

https://developer.apple.com/documentation/swift/array/reduce(_:_:)

 

reduce(_:_:) | Apple Developer Documentation

Returns the result of combining the elements of the sequence using the given closure.

developer.apple.com

 

  • 문자열을 숫자로 자료형을 바꿀 때, 옵셔널로 나온다
    • 옵셔널로 싸인 값은 사용하려면 추출이 필요하다
    • 나는 강제 추출로 ! 를 사용했다