Skip to content

Commit 7ed140e

Browse files
authored
Update 13-roman-to-integer.js
1 parent 715384f commit 7ed140e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

13-roman-to-integer.js

+23
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,26 @@ const romanToInt = function(s) {
3232
}
3333
return res
3434
}
35+
36+
37+
// another
38+
39+
/**
40+
* @param {string} s
41+
* @return {number}
42+
*/
43+
const romanToInt = function(s) {
44+
const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }
45+
let result = 0
46+
let index = s.length - 1
47+
let preInt = 0
48+
while (index >= 0) {
49+
let ch = s[index]
50+
let curInt = map[ch]
51+
if (curInt >= preInt) result += curInt
52+
else result -= curInt
53+
preInt = curInt
54+
index--
55+
}
56+
return result
57+
}

0 commit comments

Comments
 (0)