File tree 2 files changed +70
-0
lines changed
2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ impl Solution {
2
+ pub fn roman_to_int ( s : String ) -> i32 {
3
+ let s: Vec < char > = s. chars ( ) . collect ( ) ;
4
+ let mut res = 0 ;
5
+
6
+ for i in 0 ..s. len ( ) {
7
+ if i + 1 < s. len ( ) && Self :: get_value ( s[ i] ) < Self :: get_value ( s[ i + 1 ] ) {
8
+ res -= Self :: get_value ( s[ i] ) ;
9
+ } else {
10
+ res += Self :: get_value ( s[ i] ) ;
11
+ }
12
+ }
13
+
14
+ res
15
+ }
16
+
17
+ pub fn get_value ( ch : char ) -> i32 {
18
+ match ch {
19
+ 'I' => 1 ,
20
+ 'V' => 5 ,
21
+ 'X' => 10 ,
22
+ 'L' => 50 ,
23
+ 'C' => 100 ,
24
+ 'D' => 500 ,
25
+ 'M' => 1000 ,
26
+ _ => 0 ,
27
+ }
28
+ }
29
+
30
+ pub fn roman_to_int_functional ( s : String ) -> i32 {
31
+ s. chars ( ) . rfold ( 0 , |acc, ch| {
32
+ acc + match ch {
33
+ 'I' if acc >= 5 => -1 ,
34
+ 'I' => 1 ,
35
+ 'V' => 5 ,
36
+ 'X' if acc >= 50 => -10 ,
37
+ 'X' => 10 ,
38
+ 'L' => 50 ,
39
+ 'C' if acc >= 500 => -100 ,
40
+ 'C' => 100 ,
41
+ 'D' => 500 ,
42
+ 'M' => 1000 ,
43
+ _ => 0 ,
44
+ }
45
+ } )
46
+ }
47
+ }
Original file line number Diff line number Diff line change
1
+ function romanToInt ( s : string ) : number {
2
+ let roman = {
3
+ I : 1 ,
4
+ V : 5 ,
5
+ X : 10 ,
6
+ L : 50 ,
7
+ C : 100 ,
8
+ D : 500 ,
9
+ M : 1000 ,
10
+ } ;
11
+
12
+ let result = 0 ;
13
+
14
+ for ( let i = 0 ; i < s . length ; i ++ ) {
15
+ if ( i + 1 < s . length && roman [ s [ i ] ] < roman [ s [ i + 1 ] ] ) {
16
+ result -= roman [ s [ i ] ] ;
17
+ } else {
18
+ result += roman [ s [ i ] ] ;
19
+ }
20
+ }
21
+
22
+ return result ;
23
+ }
You can’t perform that action at this time.
0 commit comments