1
Fork 0
leetcode/source/roman_to_integer/mod.rs

36 lines
722 B
Rust
Raw Permalink Normal View History

2022-04-06 21:08:24 +00:00
pub fn roman_to_int(string: String) -> i32 {
let mut characters = string.chars().peekable();
let mut number = 0;
while let Some(character) = characters.next() {
let value = match character {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => unreachable!(),
2022-04-06 21:08:24 +00:00
};
if let Some(next) = characters.peek() {
let subtract = match next {
'V' | 'X' if character == 'I' => true,
'L' | 'C' if character == 'X' => true,
'D' | 'M' if character == 'C' => true,
_ => false,
};
if subtract {
number -= value;
continue;
}
}
number += value;
}
number
}