28. 없는 숫자 더하기

Harold's velog·2024년 2월 13일

CodingTest (Class)

목록 보기
28/52


import Foundation

func solution(_ numbers:[Int]) -> Int {
    
    var answer : Int = 0
    
    answer = (0...9).map{$0}.reduce(0, +) - numbers.reduce(0,+)
    
    return answer
}

없는 숫자를 더한다고해서 처음에 contains를 써야하나 고민을 하다가 생각해보니 0~9까지 더한 숫자에서 현재 배열에 가지고 있는 숫자를 더한값을 빼면 그게 없는 숫자의 총합이라는것을 알게되었고, reduce를 사용하여 간략하게 해보려고 하였다.

profile
데일리 정리, 하루에 최소 하나의 글은 적도록 하자.

0개의 댓글