본문 바로가기

javaScript/알고리즘 문제 풀이

5의 배수로 반올림하기

숫자를 매개변수로 받았을 때, 반올림이 가능한 상태를 만들어 보세요.


ex)


1
2
3
4
5
6
7
8
9
10
11
input:    output:
 
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
etc.
cs



내 답


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function roundToNext5(n){
 
  let abs=(n<0) ? Math.abs(n):n
  let num=0;
 
    for(let i=0;i<abs;i++){
    
      if(5*i<abs && abs<=5*(i+1)){
        num=i+1
      }
      
    }
 
  return n%5 ===0 ? n:(n<0 ? -5*(num-1) :5*num);
 
}
cs



best 답변으로 뽑힌 답 1


1
2
3
function roundToNext5(n){
  return Math.ceil(n/5)*5;
}
cs


best 답변으로 뽑힌 답 2


1
2
3
4
function roundToNext5(n){
  while(n % 5 !== 0) n++;
  return n;
}
cs



배운 점.


1. Mah.ceil() 메소드


1
2
3
4
5
//Math.ceil(x)
//x의 올림,x보다 크거나 같은 정수 중 가장 작은 수
 
Math.ceil(-2.2//-3
Math.ceil(2.2//3
cs



2. Math.abs() 메소드


1
2
3
4
5
//Math.abs(x)
//x의 절대값
 
Math.abs(-2//2
Math.abs(2//2
cs



3. n%5



best2 답변에서 5의 배수가 될 때까지 n이 더해지고,

아닐 경우 빠져나오도록 함수를 설계