-
Notifications
You must be signed in to change notification settings - Fork 160
/
roman-to-integer.md
56 lines (41 loc) · 2.3 KB
/
roman-to-integer.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<p>Roman numerals are represented by seven different symbols: <code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>
<pre>
<strong>Symbol</strong> <strong>Value</strong>
I 1
V 5
X 10
L 50
C 100
D 500
M 1000</pre>
<p>For example, two is written as <code>II</code> in Roman numeral, just two one's added together. Twelve is written as, <code>XII</code>, which is simply <code>X</code> + <code>II</code>. The number twenty seven is written as <code>XXVII</code>, which is <code>XX</code> + <code>V</code> + <code>II</code>.</p>
<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>
<ul>
<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9. </li>
<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90. </li>
<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>
</ul>
<p>Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.</p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> "III"
<strong>Output:</strong> 3</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> "IV"
<strong>Output:</strong> 4</pre>
<p><strong>Example 3:</strong></p>
<pre>
<strong>Input:</strong> "IX"
<strong>Output:</strong> 9</pre>
<p><strong>Example 4:</strong></p>
<pre>
<strong>Input:</strong> "LVIII"
<strong>Output:</strong> 58
<strong>Explanation:</strong> L = 50, V= 5, III = 3.
</pre>
<p><strong>Example 5:</strong></p>
<pre>
<strong>Input:</strong> "MCMXCIV"
<strong>Output:</strong> 1994
<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.</pre>