First commit, roman-to-integer
This commit is contained in:
parent
73c41cdc7c
commit
ec598dfada
2 changed files with 38 additions and 0 deletions
6
roman-to-integer/Cargo.toml
Normal file
6
roman-to-integer/Cargo.toml
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "roman-to-integer"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
32
roman-to-integer/src/main.rs
Normal file
32
roman-to-integer/src/main.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
fn roman_to_int(s: String) -> i32 {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert('I', 1);
|
||||||
|
map.insert('V', 5);
|
||||||
|
map.insert('X', 10);
|
||||||
|
map.insert('L', 50);
|
||||||
|
map.insert('C', 100);
|
||||||
|
map.insert('D', 500);
|
||||||
|
map.insert('M', 1000);
|
||||||
|
|
||||||
|
let mut result = 0;
|
||||||
|
let chars: Vec<char> = s.chars().collect();
|
||||||
|
|
||||||
|
for i in 0..chars.len() {
|
||||||
|
let current_value = map[&chars[i]];
|
||||||
|
if i < chars.len() - 1 && current_value < map[&chars[i + 1]] {
|
||||||
|
result -= current_value;
|
||||||
|
} else {
|
||||||
|
result += current_value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let roman = String::from("XXVII");
|
||||||
|
let integer = roman_to_int(roman);
|
||||||
|
println!("The integer value is: {}", integer);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue