-
Notifications
You must be signed in to change notification settings - Fork 1
/
13-roman-to-integer.js
55 lines (51 loc) · 962 Bytes
/
13-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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Problem: https://leetcode.com/problems/roman-to-integer/
* Difficulty: Easy
* Solution 1: https://www.youtube.com/watch?v=nIIe1KvP4PU
* @param {string[]} s
* @return {number}
*/
const romanToInt = (s) => {
const roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let sum = 0;
let prev = 0;
for (let i = s.length - 1; i >= 0; i--) {
const curr = roman[s[i]];
if (curr < prev) {
sum -= curr;
} else {
sum += curr;
}
prev = curr;
}
return sum;
}
// const romanToInt = (s) => {
// const obj = {
// I: 1,
// V: 5,
// X: 10,
// L: 50,
// C: 100,
// D: 500,
// M: 1000
// };
// let result = 0;
// for (let i = 0; i < s.length; i++) {
// let front = s[i], back = s[i + 1];
// if (obj[back] < obj[front]) {
// result -= obj[front];
// } else {
// result += obj[front];
// }
// }
// return result;
// }