Machineboy空
Excercism - Roman Numerals 본문
문제요약
아라비아 숫자를 로마 숫자로 변환해라
M | D | C | L | X | V | I |
1000 | 500 | 100 | 50 | 10 | 5 | 1 |
- 조건 1: 같은 글자는 3번 연속해서 나올 수 없다.
- 조건 2: 4 = 1 + 1 + 1 + 1 이 아니라 5-1 즉 IV로 표기한다.
- 4(IV)
- 9(IX)
- 40(XL)
- 90(XC)...
https://exercism.org/tracks/csharp/exercises/roman-numerals
Roman Numerals in C# on Exercism
Can you solve Roman Numerals in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
난이도
medium
풀이 포인트
- 아이디어
REVIEW
또 조건 2를 간과하고 단순히 차력 조건문을 구현했다가 보기 좋게 틀렸다.
숫자 변하는 규칙을 파악해서 적용해야한다.
큰 수일 때 그 수를 빼 간다는 것과, 900, 400 일때 수 범위를 좀 나눠서 생각해 줘야 한다는 것 생각하면 그래도 조건문으로 커버 가능한 문제.
강의 정리
https://www.youtube.com/watch?v=6fGP5IVXTxs&t=2s
지금이 중세 시대는 아니다만, 아라빅 숫자를 로마 숫자로 변환하는 게 몇몇 언어에서는 기본으로 제공하고 있는 기능이라고 한다.
CODE
using System;
using System.Linq;
public static class RomanNumeralExtension
{
public static string ToRoman(this int value)
{
string roman = "";
while (value >= 1000)
{
roman += "M";
value -= 1000;
}
if (value >= 900)
{
roman += "CM";
value -= 900;
}
if (value >= 500)
{
roman += "D";
value -= 500;
}
if (value >= 400)
{
roman += "CD";
value -= 400;
}
while (value >= 100)
{
roman += "C";
value -= 100;
}
if (value >= 90)
{
roman += "XC";
value -= 90;
}
if (value >= 50)
{
roman += "L";
value -= 50;
}
if (value >= 40)
{
roman += "XL";
value -= 40;
}
while (value >= 10)
{
roman += "X";
value -= 10;
}
if (value >= 9)
{
roman += "IX";
value -= 9;
}
if (value >= 5)
{
roman += "V";
value -= 5;
}
if (value >= 4)
{
roman += "IV";
value -= 4;
}
while (value >= 1)
{
roman += "I";
value -= 1;
}
return roman;
}
}
3연속을 나중에 체크. 우선 다 고친 다음에 변환해가는 거
using System;
using System.Linq;
public static class RomanNumeralExtension
{
public static string ToRoman(this int value) =>
string.Join("", Enumerable.Repeat("I", value))
.Replace("IIIII","V")
.Replace("IIII","IV")
.Replace("VV","X")
.Replace("VIV","IX")
.Replace("XXXXX","L")
.Replace("XXXX","XL")
.Replace("LL","C")
.Replace("LXL","XC")
.Replace("CCCCC","D")
.Replace("CCCC","CD")
.Replace("DD","M")
.Replace("DCD","CM");
}
'Computer > Coding Test' 카테고리의 다른 글
Excercism - Conway's Game of Life : DFS (0) | 2025.01.17 |
---|---|
Excercism - Scrabble Score switch문, foreach문 (1) | 2025.01.16 |
Excercism - Saddle Points 2차원 배열, 최대최소 (0) | 2025.01.15 |
Exercism - Tim from Marketing , Nullable (0) | 2025.01.14 |
Excercism - Interest is Interesting 정수형(float, double, decimal) (0) | 2025.01.14 |