roman numerals
This commit is contained in:
parent
d7e4816e05
commit
beeeb93556
6
roman-numerals/Cargo.toml
Normal file
6
roman-numerals/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "roman-numerals"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
70
roman-numerals/src/main.rs
Normal file
70
roman-numerals/src/main.rs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::io::{stdin,stdout,Write};
|
||||||
|
|
||||||
|
fn input() -> String{
|
||||||
|
let mut s=String::new();
|
||||||
|
let _=stdout().flush();
|
||||||
|
stdin().read_line(&mut s).expect("Did not enter a correct string");
|
||||||
|
if let Some('\n')=s.chars().next_back() {
|
||||||
|
s.pop();
|
||||||
|
}
|
||||||
|
if let Some('\r')=s.chars().next_back() {
|
||||||
|
s.pop();
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let mut numerals: HashMap<String, u64> = HashMap::new();
|
||||||
|
|
||||||
|
numerals.insert("I".to_string(), 1);
|
||||||
|
numerals.insert("V".to_string(), 5);
|
||||||
|
numerals.insert("X".to_string(), 10);
|
||||||
|
numerals.insert("L".to_string(), 50);
|
||||||
|
numerals.insert("C".to_string(), 100);
|
||||||
|
numerals.insert("D".to_string(), 500);
|
||||||
|
numerals.insert("M".to_string(), 1000);
|
||||||
|
|
||||||
|
let number = input();
|
||||||
|
let mut value: u64 = 4000;
|
||||||
|
let mut sum: u64 = 0;
|
||||||
|
let mut iteration = 0;
|
||||||
|
|
||||||
|
let mut skip_next = false;
|
||||||
|
|
||||||
|
let mut vector: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
for char in number.chars() {
|
||||||
|
vector.push(char.to_string());
|
||||||
|
};
|
||||||
|
|
||||||
|
for digit in vector {
|
||||||
|
if let Some(next_value) = numerals.get(&digit) {
|
||||||
|
if iteration > 0 && skip_next == false {
|
||||||
|
//println!("{}", skip_next);
|
||||||
|
//print!("{}: ", iteration);
|
||||||
|
if *next_value > value {
|
||||||
|
sum = sum + (*next_value - value);
|
||||||
|
//println!("{} = sum + ({} - {})", sum, *next_value, value);
|
||||||
|
skip_next = true;
|
||||||
|
value = *next_value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
sum = sum + value;
|
||||||
|
//println!("{} = sum + {}", sum, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
value = *next_value;
|
||||||
|
if skip_next {
|
||||||
|
skip_next = false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("digit {} does not exist (My roman numerals only go up to M)!", digit);
|
||||||
|
}
|
||||||
|
iteration += 1;
|
||||||
|
}
|
||||||
|
if skip_next == false {
|
||||||
|
sum = sum + value;
|
||||||
|
}
|
||||||
|
println!("{}",sum);
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user