문제 풀기/C#
100. 숫자 변환하기
kagan-draca
2025. 3. 21. 18:37
기본 틀 :
using System;
public class Solution {
public int solution(int x, int y, int n) {
int answer = 0;
return answer;
}
}
먼저 x와 y가 동일할 수 있기 때문에
if(x == y) return 0;
으로 0을 리턴할 수 있도록 해준다.
그 이외의 케이스들은 x가 y로 될 수 없는 케이스거나 가능한 케이스 이다.
이때, +n, * 2, * 3의 결과가 중복될 수 있기 때문에
HashSet을 사용하기로 결정했다.
그리고 계산 과정을 약간이나마 줄이기 위해서
HashSet<int> hashSet = new HashSet<int>(){x + n, x * 2, x * 3};
int count = 1;
HashSet을 만듬과 동시에 x + n, x * 2, x * 3을 초기화 해주고
그럴 경우 계산을 1번 진행한 경우이기 때문에 count를 1로 설정해줬다.
이제부터는 무한 반복을 진행하면서 y가 될 수 있는지 판별해주면 된다.
while(true)
{
if(hashSet.Contains(y)) break;
count++;
HashSet<int> temp = new HashSet<int>();
foreach(int element in hashSet)
{
int result = element + n;
if(result <= y) temp.Add(result);
result = element * 2;
if(result <= y) temp.Add(result);
result = element * 3;
if(result <= y) temp.Add(result);
}
if(temp.Count == 0) return -1;
hashSet = temp;
}
그래서, whlie 문으로 무한 반복을 시키면서 새로운 hashSet에 +n, * 2, * 3의 결과를 담아줬다.
이때, 결과가 y를 초과하는 경우는 y가 절대 될 수 없는 경우라 새로운 hashSet에 해당 결과를 담지 않았다.
그 후, 새로운 hashSet의 개수가 0이면 y가 모두 될 수 없다이므로 -1를 반환해줄 수 있게 만들었고
아닐 경우 기존 hashSet을 새로운 hashSet으로 바꿔줬다.
using System;
using System.Collections.Generic;
public class Solution {
public int solution(int x, int y, int n) {
if(x == y) return 0;
HashSet<int> hashSet = new HashSet<int>(){x + n, x * 2, x * 3};
int count = 1;
while(true)
{
if(hashSet.Contains(y)) break;
count++;
HashSet<int> temp = new HashSet<int>();
foreach(int element in hashSet)
{
int result = element + n;
if(result <= y) temp.Add(result);
result = element * 2;
if(result <= y) temp.Add(result);
result = element * 3;
if(result <= y) temp.Add(result);
}
if(temp.Count == 0) return -1;
hashSet = temp;
}
return count;
}
}