[프로그래머스 / js] 없는 숫자 더하기

jinny·2021년 9월 24일
1

프로그래머스

목록 보기
4/5
post-thumbnail

주어진 배열에서 찾을 수 없는 0~9까지 숫자를 더한 수를 출력

1. for문

function solution(num) {
    
    let answer = 0;

    for(let i=0; i<10; i++){
        if(!num.includes(i)) answer += i;
    }

    return answer;
}

let numbers = [5,8,4,0,6,7,9];
console.log(solution(numbers)); // 6
  • Array.includes(값) : 배열에서 값이 존재하면 true, 존재하지 않으면 false 반환

2. Array.reduce()

function solution(numbers) {
    return 45 - numbers.reduce((cur, acc) => cur + acc, 0);
  
}

let numbers = [5,8,4,0,6,7,9];
console.log(solution(numbers)); // 6
  • 0~9까지의 합이 45이기 때문에 [ 45 - 배열의 합 ]을 하면 없는 수의 합이 된다.
profile
주니어 개발자의 기록

0개의 댓글

관련 채용 정보