코딩테스트 연습 - 없는 숫자 더하기 | 프로그래머스 스쿨 (programmers.co.kr)
문제 설명
0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요.
제한 사항
- 1 ≤ numbers의 길이 ≤ 9
- 0 ≤ numbers의 모든 원소 ≤ 9
- numbers의 모든 원소는 서로 다릅니다.
입출력 예
numbers | result |
[1,2,3,4,6,7,8,0] | 14 |
[5,8,4,0,6,7,9] | 6 |
해결 방법
1. number 배열을 만들어서 0부터 9까지 배열에 담는다.
2. number 배열을 forEach로 돌면서 입력 값인 numbers에 값이 없다면 그 값을 더한다.
전체 코드
function solution(numbers) {
const number = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let answer = 0;
number.forEach((e) => {
if(!numbers.includes(e)){
answer += e;
}
})
return answer;
}
다른 해결 방안 코드
function solution(numbers) {
let answer = 0;
for(let i = 0; i <= 9; i++) {
if(!numbers.includes(i)) answer += i;
}
return answer;
}
만약 숫자가 커지는 경우 number 배열을 만드는 것이 아니라 for문을 통해 범위를 지정해주는 것이 더 좋을 것 같다.
function solution(numbers) {
return 45 - numbers.reduce((cur, acc) => cur + acc, 0);
}
0부터 9까지 더한 45에서 numbers 배열을 다 더한 값 경우를 빼주는 경우도 있었다. 이렇게 생각은 못해봤는데 신기했다.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JavaScript] 프로그래머스 Level 1 #폰켓몬 (0) | 2022.09.01 |
---|---|
[JavaScript] 프로그래머스 level1 #음양 더하기 (0) | 2022.08.29 |
[JavaScript] 프로그래머스 Level1 #성격 유형 검사하기 (0) | 2022.08.19 |
[JavaScript] 프로그래머스 Level1 #최소직사각형 (0) | 2022.08.18 |
[JavaScript] 프로그래머스 Level 1 #같은 숫자는 싫어 (0) | 2022.08.17 |