[프로그래머스] 연속된 수의 합

·2023년 2월 12일
0

문제 ) 연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num과 total이 주어집니다. 연속된 수 num개를 더한 값이 total이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.

function solution(num, total) {
   var answer = [];
   let mid = Math.ceil(total / num); // 4 3 4 1
   let a = Math.floor(num / 2); // 1 2 2 2
   let firstnum = mid - a; // 3 1 2 -1
   
   for(let i = 0; i < num; i++) {
       answer.push(firstnum + i); // 3 4 5
   }       
   return answer
}

함수 정리

Math.ceil() = 반올림

Math.ceil(.95);    // 1
Math.ceil(4);      // 4
Math.ceil(7.004);  // 8
Math.ceil(-0.95);  // -0
Math.ceil(-4);     // -4
Math.ceil(-7.004); // -7

Math.floor() = 반내림

Math.floor( 45.95); //  45
Math.floor( 45.05); //  45
Math.floor(  4   ); //   4
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46
profile
개발자가 되는 과정

0개의 댓글