File tree 1 file changed +50
-0
lines changed
1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/roman-to-integer/description/
3
+ * Difficulty:Easy
4
+ *
5
+ * Given a roman numeral, convert it to an integer.
6
+ * Input is guaranteed to be within the range from 1 to 3999.
7
+ */
8
+
9
+ /**
10
+ * @see https://baike.baidu.com/item/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
11
+ *
12
+ * 基本字符
13
+ * I V X L C D M
14
+ * 1 5 10 50 100 500 1000
15
+ * 相应的阿拉伯数字表示
16
+ *
17
+ * 计数方法
18
+ * 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
19
+ * 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
20
+ * 小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
21
+ * 正常使用时、连写的数字重复不得超过三次;
22
+ *
23
+ * @param {string } s
24
+ * @return {number }
25
+ */
26
+ var romanToInt = function ( s ) {
27
+
28
+ if ( ! s ) return 0 ;
29
+
30
+ var map = {
31
+ 'I' : 1 ,
32
+ 'V' : 5 ,
33
+ 'X' : 10 ,
34
+ 'L' : 50 ,
35
+ 'C' : 100 ,
36
+ 'D' : 500 ,
37
+ 'M' : 1000
38
+ } ;
39
+
40
+ var sum = map [ s [ s . length - 1 ] ] ;
41
+ for ( var i = s . length - 2 ; i >= 0 ; i -- ) {
42
+ if ( map [ s [ i ] ] < map [ s [ i + 1 ] ] ) sum -= map [ s [ i ] ] ;
43
+ else sum += map [ s [ i ] ] ;
44
+ }
45
+ return sum ;
46
+ } ;
47
+
48
+ console . log ( romanToInt ( 'III' ) , 3 ) ;
49
+ console . log ( romanToInt ( 'VI' ) , 6 ) ;
50
+ console . log ( romanToInt ( 'IV' ) , 4 ) ;
You can’t perform that action at this time.
0 commit comments