Skip to content

Commit 83664ec

Browse files
committed
Add solution #13
1 parent d5d40a3 commit 83664ec

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium|
1515
10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard|
1616
12|[Integer to Roman](./0012-integer-to-roman.js)|Medium|
17+
13|[Roman to Integer](./0013-roman-to-integer.js)|Easy|
1718
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
1819
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
1920
27|[Remove Element](./0027-remove-element.js)|Easy|

solutions/0013-roman-to-integer.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 13. Roman to Integer
3+
* https://leetcode.com/problems/roman-to-integer/
4+
* Difficulty: Easy
5+
*
6+
* Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
7+
*
8+
* Symbol Value
9+
* I 1
10+
* V 5
11+
* X 10
12+
* L 50
13+
* C 100
14+
* D 500
15+
* M 1000
16+
*
17+
* For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written
18+
* as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`.
19+
*
20+
* Roman numerals are usually written largest to smallest from left to right. However, the numeral for
21+
* four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five
22+
* we subtract it making four. The same principle applies to the number nine, which is written as `IX`.
23+
* There are six instances where subtraction is used:
24+
*
25+
* - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9.
26+
* - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90.
27+
* - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900.
28+
*
29+
* Given a roman numeral, convert it to an integer.
30+
*/
31+
32+
/**
33+
* @param {string} s
34+
* @return {number}
35+
*/
36+
var romanToInt = function(s) {
37+
const map = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 };
38+
39+
return s.split('').reduce((result, v, i) => {
40+
result += map[v] >= map[s[i + 1]] || s.length === i + 1
41+
? map[v]
42+
: -1 * map[v];
43+
return result;
44+
}, 0);
45+
};

0 commit comments

Comments
 (0)