leetcode: solve problem 13

This commit is contained in:
Ivan R. 2024-02-15 11:48:04 +05:00
parent b03cabc268
commit 615aa114f2
Signed by: lumin
GPG key ID: 927D3132247BDE4E
3 changed files with 129 additions and 0 deletions

View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "roman-to-integer"
version = "0.1.0"

View file

@ -0,0 +1,8 @@
[package]
name = "roman-to-integer"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,114 @@
pub fn roman_to_int(s: String) -> i32 {
let mut res = 0;
let v: Vec<char> = s.chars().collect();
let mut check_prev = true;
for (i, ch) in v.iter().enumerate() {
let prev = if i > 0 { v[i - 1] } else { '0' };
match prev {
'I' => match *ch {
'V' => {
res += 4;
check_prev = false;
continue;
}
'X' => {
res += 9;
check_prev = false;
continue;
}
_ => (),
},
'X' => match *ch {
'L' => {
res += 40;
check_prev = false;
continue;
}
'C' => {
res += 90;
check_prev = false;
continue;
}
_ => {}
},
'C' => match *ch {
'D' => {
res += 400;
check_prev = false;
continue;
}
'M' => {
res += 900;
check_prev = false;
continue;
}
_ => {}
},
_ => (),
}
if check_prev && (prev == 'I' || prev == 'X' || prev == 'C') {
res += char_to_int(prev);
}
check_prev = true;
if *ch != 'I' && *ch != 'X' && *ch != 'C' {
res += char_to_int(*ch);
}
}
if check_prev {
let l = v[v.len() - 1];
if l == 'I' || l == 'X' || l == 'C' {
res += char_to_int(l);
}
}
res
}
fn char_to_int(c: char) -> i32 {
match c {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => 0,
}
}
#[cfg(test)]
mod tests {
use crate::roman_to_int;
#[test]
fn simple_test() {
let result = roman_to_int("III".to_string());
assert_eq!(result, 3);
}
#[test]
fn advanced_test() {
let result = roman_to_int("LVIII".to_string());
assert_eq!(result, 58);
}
#[test]
fn sub() {
let result = roman_to_int("MCMXCIV".to_string());
assert_eq!(result, 1994);
}
#[test]
fn simple_sub() {
let result = roman_to_int("IX".to_string());
assert_eq!(result, 9);
}
}