-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman-to-integer.rs
66 lines (62 loc) · 1.88 KB
/
roman-to-integer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
struct Solution;
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let mut ans: i32 = 0;
let mut prev: Option<char> = None;
for i in s.chars().rev() {
let now = prev;
prev = Some(i);
match i {
'I' => {
if let Some(n) = now {
if n == 'V' || n == 'X' {
ans -= 1;
continue;
}
}
ans += 1;
}
'X' => {
if let Some(n) = now {
if n == 'L' || n == 'C' {
ans -= 10;
continue;
}
}
ans += 10;
}
'C' => {
if let Some(n) = now {
if n == 'D' || n == 'M' {
ans -= 100;
continue;
}
}
ans += 100;
}
'V' => ans += 5,
'L' => ans += 50,
'D' => ans += 500,
'M' => ans += 1000,
_ => {}
}
}
ans
}
}
fn main() {
println!("{}", Solution::roman_to_int("III".to_string()));
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test() {
assert_eq!(Solution::roman_to_int("III".to_string()), 3);
assert_eq!(Solution::roman_to_int("IV".to_string()), 4);
assert_eq!(Solution::roman_to_int("IX".to_string()), 9);
assert_eq!(Solution::roman_to_int("LVIII".to_string()), 58);
assert_eq!(Solution::roman_to_int("DCXXI".to_string()), 621);
assert_eq!(Solution::roman_to_int("MCMXCIV".to_string()), 1994);
}
}