기본 틀 :
using System;
class Solution
{
public int solution(int n, int a, int b)
{
int answer = 0;
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
System.Console.WriteLine("Hello C#");
return answer;
}
}
문제를 보고 while 문으로 횟수를 구해야겠다고는 생각했다.
그리고 각 라운드 마다 a, b가 2로 나눠지는데
이때, a와 b가 홀수이면 +1을 해주면 됐다.
(그럴 경우 a와 b가 0이 되는 현상도 방지 가능)
using System;
using static System.Math;
class Solution
{
public int solution(int n, int a, int b)
{
int answer = 0;
while(a != b)
{
if(a % 2 == 0) a /= 2;
else if(a % 2 == 1)
{
a /= 2;
a++;
}
if(b % 2 == 0) b /= 2;
else if(b % 2 == 1)
{
b /= 2;
b++;
}
answer++;
}
return answer;
}
}
문제를 풀고 다른 사람들의 풀이를 찾아봤다.
다른 사람 풀이 1)
using System;
using static System.Math;
class Solution
{
public int solution(int n, int a, int b)
{
int answer = 0;
while(a != b)
{
a = a / 2 + a % 2;
b = b / 2 + b % 2;
answer++;
}
return answer;
}
}
위의 풀이를 보고 놀란 이유는
X / 2 + X % 2
if문 없이 a와 b가 짝수일 때는 % 2가 0이므로 1이 더하지지 않도록 만고,
홀수일 때는 % 2가 1이므로 1을 더해 전체 결과가 짝수이거나 1이 될 수 있게 만든 것이다.
(위의 방식으로 0이 되는 현상도 방지 가능)
다른 사람 풀이 2)
using System;
using static System.Math;
class Solution
{
public int solution(int n, double a, double b)
{
int answer = 0;
while(a != b)
{
a = Math.Ceiling(a / 2);
b = Math.Ceiling(b / 2);
answer++;
}
return answer;
}
}
위의 코드는 매개변수를 double로 실수형으로 만들어
Math.Ceiling을 사용해 올림을 해준 것이다.
이 경우도 마찬가지로 if문 없이
a와 b가 0이 되는 현상을 방지할 수 있고
a와 b가 1이 아닌 홀수일 경우 짝수로 변경 가능하다는 점이었다.
하지만, 자료형을 실수형으로 사용해 소수점 계산으로 수행시간이 더 긴 것을 볼 수 있다.
'문제 풀기 > C#' 카테고리의 다른 글
82. 멀리 뛰기 (0) | 2025.02.28 |
---|---|
81. N개의 최소공배수 (0) | 2025.02.28 |
79. 카펫 (0) | 2025.02.26 |
78. 피보나치 (0) | 2025.02.25 |
77. 이진 변환 반복하기 (Convert.int32, Convert.ToString) (0) | 2025.02.25 |