저장을 습관화
프로그래머스 LV.0 연속된 수의 합 본문
프로그래머스 LV.0 연속된 수의 합
https://school.programmers.co.kr/learn/courses/30/lessons/120923
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 명
연속된 수의 합
2. 문제 설명
연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num과 total이 주어집니다. 연속된 수 num개를 더한 값이 total이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.
3. 제한 사항
1 ≤ num ≤ 100
0 ≤ total ≤ 1000
num개의 연속된 수를 더하여 total이 될 수 없는 테스트 케이스는 없습니다.
4. 예시
num | total | result |
3 | 12 | [3, 4, 5] |
5 | 15 | [1, 2, 3, 4, 5] |
4 | 14 | [2, 3, 4, 5] |
5 | 5 | [-1, 0, 1, 2, 3] |
5. 기본 제공 코드
function solution(num, total) {
var answer = [];
return answer;
}
6. 제출한 내 답
const solution = (num, total) => {
let start = -49;
let result = ['element'];
while (result.reduce((acc, cur) => (acc += cur), 0) !== total) {
result = [];
for (i = 0; i < num; i++) {
result.push(start + i);
}
start += 1;
}
return result;
};
6-2. VSC에 작성한 내용
const solution = (num, total) => {
/** num은 연속되는 숫자의 개수
* total은 num을 모두 더해 만들 수
*/
let start = -49;
let result = ['element'];
while (result.reduce((acc, cur) => (acc += cur), 0) !== total) {
result = [];
for (i = 0; i < num; i++) {
result.push(start + i);
}
start += 1;
}
return result;
};
// test
console.log(solution(3, 12));
console.log(solution(5, 15));
console.log(solution(4, 14));
console.log(solution(5, 5));
console.log(solution(5, 0));
console.log(solution(3, 0));
7. 특이사항
없음
8. 다른 사람이 작성한 답
8-1.
function solution(num, total) {
var min = Math.ceil(total/num - Math.floor(num/2));
var max = Math.floor(total/num + Math.floor(num/2));
return new Array(max-min+1).fill(0).map((el,i)=>{return i+min;});
}
'코딩 테스트 > 프로그래머스 - 자바스크립트' 카테고리의 다른 글
프로그래머스 LV.0 문자열 밀기 (0) | 2024.02.28 |
---|---|
프로그래머스 LV.0 다음에 올 숫자 (0) | 2024.02.27 |
프로그래머스 LV.0 특이한 정렬 (0) | 2024.02.26 |
프로그래머스 LV.0 유한소수 판별하기 (0) | 2024.02.25 |
프로그래머스 LV.0 평행 (0) | 2024.02.24 |