題目描述:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2
is written as II
in Roman numeral, just two one’s added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.
Example 1:
Input: num = 3
Output: "III"
Example 2:
Input: num = 4
Output: "IV"
Example 3:
Input: num = 9
Output: "IX"
Example 4:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= num <= 3999
一刷題解(Brute Force + Recursion):
這題給我們一個取值範圍 1 – 3999的正整數,然後要我們把這個正整數轉換成羅馬數字。最簡單粗暴的方法就是直接Brute Force,把千位百位十位個位的數字逐一加到字符串裡。
通過檢查這個數字是否大於1000/100/10,決定用甚麼羅馬數字。如果數字大於1000,就把數字除以1000,從而知道具體是「幾千」,最後再根據幾千來進行多少次遍歷,把對應「千」的羅馬數字”M”加到字符串裡,最後通過求模去掉數字的千位,進行遞歸後繼續執行百位十位個位的運算。
唯一要注意的點就是4和9十/百的特殊情況,需要另外單獨處理(如:IV/IX)。
public class Solution {
public string IntToRoman(int num) {
StringBuilder sb = new StringBuilder();
Translator(num, sb);
return sb.ToString();
}
void Translator(int num, StringBuilder sb)
{
if(num <= 0){ return; }
//How many digit and check first number
if(num >= 1000)
{
//1000 - 3999
int thousands = num / 1000;
for(int i = 0; i < thousands; i++)
{
sb.Append("M");
}
num = num % 1000;
}
else if(num >= 100)
{
//100 - 999
int hundreds = num / 100;
if(hundreds == 9)
{
sb.Append("CM");
}
else if(hundreds >= 4)
{
if(hundreds == 4)
{
sb.Append("CD");
}
else
{
sb.Append("D");
for(int i = 0; i < hundreds - 5; i++)
{
sb.Append("C");
}
}
}
else
{
for(int i = 0; i < hundreds; i++)
{
sb.Append("C");
}
}
num = num % 100;
}
else if(num >= 10)
{
//10 - 99
int decades = num / 10;
if(decades == 9)
{
sb.Append("XC");
}
else if(decades >= 4)
{
if(decades == 4)
{
sb.Append("XL");
}
else
{
sb.Append("L");
for(int i = 0; i < decades - 5; i++)
{
sb.Append("X");
}
}
}
else
{
for(int i = 0; i < decades; i++)
{
sb.Append("X");
}
}
num = num % 10;
}
else
{
//1 - 9
if(num == 9)
{
sb.Append("IX");
}
else if(num >= 4)
{
if(num == 4)
{
sb.Append("IV");
}
else
{
sb.Append("V");
for(int i = 0; i < num - 5; i++)
{
sb.Append("I");
}
}
}
else
{
for(int i = 0; i < num; i++)
{
sb.Append("I");
}
}
num = num % 1;
}
Translator(num, sb);
}
}