주녘공부일지

[프로그래머스 C#] Lv.2 숫자 변환하기 본문

Programmers - C#/CodingTest Lv.2

[프로그래머스 C#] Lv.2 숫자 변환하기

주녘 2023. 9. 7. 19:31
728x90

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

 

프로그래머스

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

programmers.co.kr

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

- 최소 연산 횟수를 구하는 문제기 때문에 연산 전, 후로 구분하여 체크

- 연산 전 List<T>, 연산 후 HashSet<T>

https://godgjwnsgur7.tistory.com/46

 

[C#] 자료구조 정리 (Dict, List, Queue, Stack, HashSet 등)

자료구조(Data Structure)란? 데이터를 효율적으로 접근하고 조작할 수 있게 데이터 구조를 만들어 관리하는 것 - Collections은 C#에서 지원하는 자료구조 클래스 using System.Collections.Generic; 제네릭 컬렉

godgjwnsgur7.tistory.com

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        public int solution(int x, int y, int n)
        {
            int answer = 0; // 연산 카운트
            List<int> list = new List<int>(); // 연산 전
            HashSet<int> hs = new HashSet<int>(); // 연산 후

            // 초기 값
            list.Add(x);

            // 예외처리
            if (x == y)
                return 0;

            // 연산 할 대상이 없을 때까지 수행
            while (list.Count != 0)
            {
                answer++;

                // 연산
                foreach (int num in list)
                {
                    if (num > y)
                        continue;

                    hs.Add(num + n);
                    hs.Add(num * 2);
                    hs.Add(num * 3);
                }

                // 값 찾음
                if (hs.Contains(y))
                    return answer;

                // 연산 전, 후 세팅
                list.Clear();
                list = new List<int>(hs);
                hs.Clear();
            }

            return -1; // 불가능
        }
    }
728x90