File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ / * *
2+ * Question :
3+ * Given a roman numeral , convert it to an integer .
4+ * Input is guaranteed to be within the range from 1 to 3999.
5+ * Tag :
6+ * Math , String
7+ *
8+ * 注: 将罗马数字转为阿拉伯数字 如 'XLV' == 45
9+ * 罗马数字规则:
10+ * 1. 重复数次:一个罗马数字重复几次,就表示这个数的几倍。
11+ * 2. 右加左减 , 较大的数的右边跟着较小的数,表示大数加小数,反之大减小。
12+ * 左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV。 ( 此处忽略 )
13+ * 左减数字必须為一位,比如8写成VIII,而非IIX。 (此处忽略 )
14+ *
15+ * /
116
17+ //遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数
18+
19+ var romanToInt = function ( s ) {
20+ var rToIMap = {
21+ 'I' : 1 ,
22+ 'V' : 5 ,
23+ 'X' : 10 ,
24+ 'L' : 50 ,
25+ 'C' : 100 ,
26+ 'D' : 500 ,
27+ 'M' : 1000
28+ }
29+ var result = rToIMap [ s [ s . length - 1 ] ] ;
30+
31+ for ( var i = s . length - 2 ; i >= 0 ; i -- ) {
32+ var currNum = rToIMap [ s [ i ] ] ,
33+ afterNum = rToIMap [ s [ i + 1 ] ] ;
34+
35+ if ( currNum >= afterNum ) {
36+ result += currNum ;
37+ } else {
38+ result -= currNum ;
39+ }
40+ }
41+
42+ return result ;
43+ } ;
You can’t perform that action at this time.
0 commit comments