forked from JackPu/JavaScript-Algorithm-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroman-to-integer.js
39 lines (38 loc) · 846 Bytes
/
roman-to-integer.js
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
// https://leetcode.com/problems/roman-to-integer/description/
// https://en.wikipedia.org/wiki/Roman_numerals
/**
* example "DCXXI" => 621
*/
module.exports = function (s) {
const romanLetters = {
'M': 1000,
'CM': 900,
'D': 500,
'CD': 400,
'C': 100,
'XC': 90,
'L': 50,
'XL': 40,
'X': 10,
'IX': 9,
'V': 5,
'IV': 4,
'I': 1,
};
const arr = s.split('');
let index = 0;
let num = 0
let key = ''
for (let i = 0; i<arr.length; i++) {
const key = arr[i]
if(key !== 'V' || key !== 'M') {
if(romanLetters[key + arr[i+1]]) {
num += romanLetters[key + arr[i+1]]
i += 1
continue
}
}
num += romanLetters[key]
}
return num
}