[Programmers] [Lv.1] [Swift] 자릿수 더하기

doyeonjeong_·2022년 7월 23일
0

프로그래머스

목록 보기
8/35

문제

자릿수 더하기

풀이


import Foundation

func solution(_ n:Int) -> Int {
    return "\(n)".compactMap{$0.wholeNumberValue}.reduce(0, +)
}

🤔 FEEDBACK

  • 바로 직전에 배운 "\(n)".compactMap{}를 사용했다.
  • 근데 reduce하고 compactMap도 O(n)이라서 생각보다 빠르지 않았다.

다른 풀이


import Foundation

func solution(_ n:Int) -> Int {
    return String(n).reduce(0, {$0+Int(String($1))!});
}
  • Array만 reduce 될거라고 생각했는데 두번째 인자를 {$0+Int(String($1))!}하면 되는구나.. 🙄

Reference

profile
블로그 이사중 🚚 byukbyak.tistory.com

0개의 댓글