DEV Community

Discussion on: Solution: Roman to Integer

Collapse
 
mochidaz profile image
Rahman

This one's written in Rust. Used macro rules for hashmap so that i won't have to insert all the romans and their values one by one into the hashmap.

use std::collections::HashMap;

macro_rules! hashmap {
    ($( $key: expr => $val: expr ),*) => {{
         let mut map = ::std::collections::HashMap::new();
         $( map.insert($key, $val); )*
         map
    }}
}

impl Solution {
    pub fn roman_to_int(s: String) -> i32 {
        let mut ans: i32 = 0;

        let map = hashmap!["I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000];

        s.chars().rev().into_iter().for_each(|c| {
            let mut num = map.get(c.to_string().as_str()).unwrap();
            if 4 * num < ans {
                ans -= num;
            }
            else {
                ans += num;
            };
        });
        ans
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
t3chnicallyinclined profile image
t3chnicallyinclined • Edited

Thanks for the help, after digging into each method I found the following:

There's no need for: .into_iter() since the rev() method returns an interator
and num does not need to be mutable in this case.

So here would be a little leaner version:

use std::collections::HashMap;

impl Solution {
    pub fn roman_to_int(s: String) -> i32 {
        let mut ans: i32  = 0;

        let map = HashMap::from([
            ("I", 1),
            ("V", 5),
            ("X", 10),
            ("L", 50),
            ("C", 100),
            ("D", 500),
            ("M", 1000),
        ]);

        s.chars().rev().for_each(|c| {
            let num = map.get(c.to_string().as_str()).unwrap();

            if 4 * num < ans {
                ans -= num;
            }
            else {
                ans += num;
            };

        });
        ans
    }
}
Enter fullscreen mode Exit fullscreen mode