본문 바로가기
코딩테스트(알고리즘)/프로그래머스

[프로그래머스] 마법의 엘리베이터 (Javascript)

by Cafe Mocha 2023. 2. 12.

https://school.programmers.co.kr/learn/courses/30/lessons/148653

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


알고리즘 : 구현, 그리디

 

function solution(storey) {
   
    storey = storey.toString().split("").map(v=>+v);

  // -1, +1 -10, +10, -100,+100

  // 내가 있는 층 -> 0이되는 최소값!
  // 1,10,100,1000,10000 .... 100000000
  // 어디와 가까운지 확인해야함-> 자리수?



  // 각 자리수 별로 가까운 거리를 확인?
  let cnt =0;

  while(storey.length){
    let num = storey.pop();
    if(num<=4) {
      cnt+=num;
    } else if (num>=6) {
      cnt+= 10 - num;
      if(storey.length) storey[storey.length-1]+=1;
      else storey.unshift(1);
    } else {
      if(storey.length && storey[storey.length-1]>=5){
        storey[storey.length-1]+=1;
      }
      cnt+=num;
    }
  }

  console.log(cnt);
    
    
    return cnt;
}