# 【LeetCode】 12. Integer to Roman
## Description
> 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, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven 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 before V (5) and X (10) to make 4 and 9.
> - X can be placed before L (50) and C (100) to make 40 and 90.
> - C can be placed before D (500) and M (1000) to make 400 and 900.
> Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
> 羅馬數字用七個符號來表示數字:I、V、X、L、C、D和M。
> 分別對應到的數字請參照上方。
> 舉例來說,"二"在羅馬數字中我們會寫成"II",代表兩個一相加;"十二"則是寫成"XII",也就是X + II;"二十七"則是寫成"XXVII",代表XX + V + II。
> 羅馬數字通常從大到小會左到右的順序撰寫,然而數字"四"卻不是寫成"IIII",取而代之的是"IV",一在五之前代表的是五要減掉一。同樣的,數字九會寫成IX。我們直接列出六種所有可能的減法情形給你:
> - I可以放在V(5)和X(10)前面來完成4和9。
> - X可以放在L(50)和C(100)前面來完成40和90。
> - C可以放在D(500)和M(1000)前面來完成400和900。
> 給予一個一般整數,請將它轉換為羅馬數字。數字大小只會在1到3999之間。
## Example:
```
Example 1:
Input: 3
Output: "III"
Example 2:
Input: 4
Output: "IV"
Example 3:
Input: 9
Output: "IX"
Example 4:
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
```
## Solution
* 按照規則硬爆開來即可。
* 根據`num`大小去寫入字母,同時減少`num`直到`num`為零;遇到`4`、`9`開頭的數字另外處理。
* 也許可以寫成`Enumeration`或是`Function`的方式,讓整個程式更乾淨。
### Code
```C++=1
class Solution {
public:
string intToRoman(int num) {
string str;
while(num!=0)
{
if(num>=1000)
{
num-=1000;
str+="M";
}
else if(num>=900)
{
num-=900;
str+="CM";
}
else if(num>=500)
{
num-=500;
str+="D";
}
else if(num>=400)
{
num-=400;
str+="CD";
}
else if(num>=100)
{
num-=100;
str+="C";
}
else if(num>=90)
{
num-=90;
str+="XC";
}
else if(num>=50)
{
num-=50;
str+="L";
}
else if(num>=40)
{
num-=40;
str+="XL";
}
else if(num>=10)
{
num-=10;
str+="X";
}
else if(num>=9)
{
num-=9;
str+="IX";
}
else if(num>=5)
{
num-=5;
str+="V";
}
else if(num>=4)
{
num-=4;
str+="IV";
}
else
{
num-=1;
str+="I";
}
}
return str;
}
};
```
###### tags: `LeetCode` `C++`