[알고리즘 문제 풀기] 로마 숫자(2608)

C#
lhs's avatar
Feb 24, 2025
[알고리즘 문제 풀기] 로마 숫자(2608)
notion image

1. 문제 풀이 아이디어

  • 함수를 구현하여 로마 숫자를 정수로 변환하고 두 수를 더한 후, 다시 로마 숫자로 변환하여 출력해 문제를 해결한다.

2. 나의 정답 코드

using (StreamReader sr = new StreamReader(Console.OpenStandardInput())) using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput())) { string sA = sr.ReadLine(); string sB = sr.ReadLine(); int iA = ToInt(sA); int iB = ToInt(sB); int iC = iA + iB; string sC = ToString(iC); sw.WriteLine(iC + "\n" + sC); } int ToInt(string s) { int result = 0; bool[] chk = new bool[3]; for (int i = 0; i < s.Length; i++) { switch (s[i]) { case 'I': result += 1; break; case 'V': if (i > 0 && s[i - 1] == 'I') result += 3; else result += 5; break; case 'X': if (i > 0 && s[i - 1] == 'I') result += 8; else result += 10; break; case 'L': if (i > 0 && s[i - 1] == 'X') result += 30; else result += 50; break; case 'C': if (i > 0 && s[i - 1] == 'X') result += 80; else result += 100; break; case 'D': if (i > 0 && s[i - 1] == 'C') result += 300; else result += 500; break; case 'M': if (i > 0 && s[i - 1] == 'C') result += 800; else result += 1000; break; } } return result; } string ToString(int n) { string result = ""; int thousand = n / 1000; while (thousand > 0) { result += "M"; thousand--; } int hund = n % 1000 / 100; if (hund == 4) result += "CD"; else if (hund == 9) result += "CM"; else { if (hund >= 5) { result += "D"; hund -= 5; } while (hund > 0) { result += "C"; hund--; } } int ten = n % 100 / 10; if (ten == 4) result += "XL"; else if (ten == 9) result += "XC"; else { if (ten >= 5) { result += "L"; ten -= 5; } while (ten > 0) { result += "X"; ten--; } } int one = n % 10; if (one == 4) result += "IV"; else if (one == 9) result += "IX"; else { if (one >= 5) { result += "V"; one -= 5; } while (one > 0) { result += "I"; one--; } } return result; }

3. 정리

  • ToInt 함수를 구현해 로마 숫자를 정수로 변환한다.
  • 작은 숫자가 앞에 올 경우 빼는 방식으로 값을 조정한다.
  • ToString 함수에서 정수를 로마 숫자로 변환한다.
  • 큰 자리부터 처리하며, 4와 9의 경우 특수한 로마 숫자 표기법을 적용한다.
  • 입력받은 두 개의 로마 숫자를 변환하여 더한 후, 다시 로마 숫자로 변환하여 출력한다.
Share article

LHS's Study Space