In this post, I’ll be showing you how we can convert Roman Numbers to an integer value in Rust.

First of all, a kind reminder, it is my solution to that problem. Yours could totally be different. 😊
Let’s start with creating a rust module. I’ll call it roman_numbers.rs. To be able to define a static HashMap that holds all the roman numbers and the integer equivalent of them. As this static data will be outside of our main function, we can define it as lazy static with lazy_static module. In order to use it in your project, you must add this line in your cargo.toml.
[dependencies]
lazy_static = "1.5.0"
Then the content of the roman_numbers.rs file will be as following;
use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref map: HashMap<char, i32> = HashMap::from([
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000)
]);
}
pub fn to_number(roman_numbers: &str) -> Result<i32, String> {
let mut total = 0;
let mut last_value = 0;
for c in roman_numbers.chars().rev() {
let current_value = map.get(&c).ok_or("character could not be recognized")?;
if *current_value >= last_value {
total += *current_value;
} else {
total -= *current_value;
}
last_value = *current_value;
}
Ok(total)
}
My approach here was to iterate through the letters and validate if it is in my mapping. if not, return an error with a valid message.
if we have it already then store it for the next comparison. The comparison basically compares the current and the previous letters values. It is because, in roman letters, we might have minus values. Imagine, XV means 15 as integer. However, if you like to say 14, you cannot go with XIIII. The rule says, no letter can be repeated more than 3 times. Instead of using ‘I‘ four times, we will have to subtract it from the value which is one level higher than that. like XIV. In this context, as the third letter ‘V‘ is higher than its previous letter, which is ‘I‘, the letter of ‘I‘ would have to be subtracted from ‘V‘.
The if statement in the code, emphasises this situation. The rest is simple summation.
The usage example would be;
let roman_letters = "MCMVII";
let number = to_number(roman_letters);
print!("Result -> {}", number.unwrap());
In terms of the function, the ‘C‘ will be subtracted from ‘M‘ and the result would be;
Result -> 1907
I hope you enjoyed reading. Please let me know your solutions.