File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @return {number }
4
+ */
5
+ var romanToInt = function ( s ) {
6
+ let romans = {
7
+ I : 1 ,
8
+ V : 5 ,
9
+ X : 10 ,
10
+ L : 50 ,
11
+ C : 100 ,
12
+ D : 500 ,
13
+ M : 1000 ,
14
+ } ;
15
+
16
+ let arr = s . split ( "" ) ;
17
+
18
+ let sum = 0 ;
19
+
20
+ for ( let i = arr . length - 1 ; i >= 0 ; i -- ) {
21
+ // IV : 4
22
+ if ( romans [ arr [ i ] ] === romans [ "V" ] ) {
23
+ if ( romans [ arr [ i - 1 ] ] === romans [ "I" ] ) {
24
+ sum -= 1 * 2 ;
25
+ }
26
+ }
27
+ // IX : 4
28
+ if ( romans [ arr [ i ] ] === romans [ "X" ] ) {
29
+ if ( romans [ arr [ i - 1 ] ] === romans [ "I" ] ) {
30
+ sum -= 1 * 2 ;
31
+ }
32
+ }
33
+ // XL : 40
34
+ if ( romans [ arr [ i ] ] === romans [ "L" ] ) {
35
+ if ( romans [ arr [ i - 1 ] ] === romans [ "X" ] ) {
36
+ sum -= 10 * 2 ;
37
+ }
38
+ }
39
+ // XC : 90
40
+ if ( romans [ arr [ i ] ] === romans [ "C" ] ) {
41
+ if ( romans [ arr [ i - 1 ] ] === romans [ "X" ] ) {
42
+ sum -= 10 * 2 ;
43
+ }
44
+ }
45
+ // CD : 400
46
+ if ( romans [ arr [ i ] ] === romans [ "D" ] ) {
47
+ if ( romans [ arr [ i - 1 ] ] === romans [ "C" ] ) {
48
+ sum -= 100 * 2 ;
49
+ }
50
+ }
51
+ // CM : 900
52
+ if ( romans [ arr [ i ] ] === romans [ "M" ] ) {
53
+ if ( romans [ arr [ i - 1 ] ] === romans [ "C" ] ) {
54
+ sum -= 100 * 2 ;
55
+ }
56
+ }
57
+
58
+ sum += romans [ arr [ i ] ] ;
59
+ }
60
+
61
+ return sum ;
62
+ } ;
63
+
64
+ // Runtime: 148 ms, faster than 80.16% of JavaScript online submissions for Roman to Integer.
65
+ // Memory Usage: 47.5 MB, less than 18.15% of JavaScript online submissions for Roman to Integer.
You can’t perform that action at this time.
0 commit comments