주녘공부일지

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

Programmers - C#/CodingTest Lv.2

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

주녘 2023. 8. 18. 17:16
728x90

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

 

프로그래머스

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

programmers.co.kr

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;
            }

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] >= 10)
                {
                    if (i + 1 < list.Count)
                        list[i + 1]++;
                    else
                        answer++;
                }
                else if (list[i] < 5)
                {
                    answer += list[i];
                }
                else if (list[i] > 5)
                {
                    answer += 10 - list[i];
                    if (i + 1 < list.Count)
                        list[i + 1]++;
                    else
                        answer++;
                }
                else if (list[i] == 5)
                {
                    answer += list[i];

                    if (i + 1 < list.Count && list[i + 1] >= 5)
                        list[i + 1]++;
                }
                else
                    return -1;
            }

            return answer;
        }
    }
728x90