Created
January 5, 2023 07:10
-
-
Save zRains/9d094b27cb05706af4bc48eb138f1320 to your computer and use it in GitHub Desktop.
Interconversion of roman and integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
struct Solution; | |
impl Solution { | |
pub fn int_to_roman(int: i32) -> String { | |
let thousands = ["", "M", "MM", "MMM"]; | |
let hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; | |
let tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; | |
let ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; | |
let mut str_arr = Vec::<&str>::new(); | |
str_arr.push(thousands[(int as f32 / 1000.0).floor() as usize]); | |
str_arr.push(hundreds[((int % 1000) as f32 / 100.0) as usize]); | |
str_arr.push(tens[((int % 100) as f32 / 10.0) as usize]); | |
str_arr.push(ones[(int % 10) as usize]); | |
str_arr.join("").into() | |
} | |
pub fn roman_to_int(s: String) -> i32 { | |
let map = HashMap::<&str, i32>::from([ | |
("I", 1), | |
("V", 5), | |
("X", 10), | |
("L", 50), | |
("C", 100), | |
("D", 500), | |
("M", 1000), | |
]); | |
let mut romans = s | |
.split("") | |
.filter(|r| r.len() != 0) | |
.map(|r| map.get(r).expect("Unexpected roman char")) | |
.collect::<Vec<&i32>>(); | |
romans.reverse(); | |
let mut res = romans[0].clone(); | |
for idx in 1..romans.len() { | |
if romans[idx] >= romans[idx - 1] { | |
res += romans[idx].clone(); | |
} else { | |
res -= romans[idx].clone(); | |
} | |
} | |
res | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment