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 } }
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.
.into_iter()
rev()
num
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 } }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.
Thanks for the help, after digging into each method I found the following:
There's no need for:
.into_iter()
since therev()
method returns an interatorand
num
does not need to be mutable in this case.So here would be a little leaner version: