주녘공부일지

[프로그래머스 C#] Lv.2 마법의 엘리베이터 본문

CodingTest/Programmers Lv.2

[프로그래머스 C#] Lv.2 마법의 엘리베이터

주녘 2024. 9. 24. 10:45

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

 

프로그래머스

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

programmers.co.kr

 

1. 정답코드 및 핵심 아이디어, 유의사항

마법의 엘리베이터 문제

- 만약 자릿수가 증가된다면 다음 자리 값에 영향을 주므로 역순으로 1의 자리 수 부터 확인

- 만약 5인 경우 다음 자리 수가 5 이상인지 확인하여 5 이상이라면 자릿수를 증가

 

코드 참조

using System;
using System.Collections.Generic;

public class Solution
{
    public int solution(int storey)
    {
        int answer = 0;
        List<int> list = new List<int>();
        
        while(storey > 0)
        {
            list.Add(storey % 10);
            storey /= 10;
        }
        list.Add(0);
        
        for(int i = 0; i < list.Count - 1; i++)
        {
            if(list[i] == 5 && list[i + 1] >= 5)
            {
                list[i + 1] += 1;
                answer += 5;
            }
            else if(list[i] > 5)
            {
                list[i + 1] += 1;
                answer += (10 - list[i]);
            }
            else // list[i] <= 5
            {
                answer += list[i];
            }
        }
        
        return answer + list[list.Count - 1];
    }
}