Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Hints:
基本字符 |
I
|
V
|
X
|
L
|
C
|
D
|
M
|
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 |
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
- 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
- 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
- 小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
- 基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;
- 不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;
- V 和 X 左边的小数字只能用 I;
- L 和 C 左边的小数字只能用 X;
- D 和 M 左边的小数字只能用 C。
TestCases:
- 3 -> III
- 4 -> IV
- 6 -> VI
- 9 -> IX
- 19 -> XIX
- 20 -> XX
- 45 -> XLV
- 1980 -> MCMLXXX
- 3999 -> MMMCMXCIX
My Code
class Solution {
public:
string intToRoman(int num) {
char romanNums[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
string result = "";
int thousandDigit = num / 1000;
num %= 1000;
for (int i = 0; i < thousandDigit; i++)
result += 'M';
int hundredDigit = num / 100;
num %= 100;
if (hundredDigit <= 3)
{
for (int i = 0; i < hundredDigit; i++)
result += 'C';
}
else if (hundredDigit == 4)
result += "CD";
else if (hundredDigit <= 8)
{
result += 'D';
for (int i = 0; i < hundredDigit - 5; i++)
result += 'C';
}
else if (hundredDigit == 9)
result += "CM";
int tenDigit = num / 10;
num %= 10;
if (tenDigit <= 3)
{
for (int i = 0; i < tenDigit; i++)
result += 'X';
}
else if (tenDigit == 4)
result += "XL";
else if (tenDigit <= 8)
{
result += 'L';
for (int i = 0; i < tenDigit - 5; i++)
result += 'X';
}
else if (tenDigit == 9)
result += "XC";
int singleDigit = num;
if (singleDigit <= 3)
{
for (int i = 0; i < singleDigit; i++)
result += 'I';
}
else if (singleDigit == 4)
result += "IV";
else if (singleDigit <= 8)
{
result += 'V';
for (int i = 0; i < singleDigit - 5; i++)
result += 'I';
}
else if (singleDigit == 9)
result += "IX";
return result;
}
};
Runtime:
28 ms