1
Fork 0

Solve integer-to-roman.

This commit is contained in:
Bauke 2022-04-10 16:08:30 +02:00
parent 61dcce1a76
commit 2847166137
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,31 @@
pub fn int_to_roman(number: i32) -> String {
let mut result = String::new();
for (index, digit) in number.to_string().chars().rev().enumerate() {
if digit == '0' {
continue;
}
let digit = digit.to_digit(10).unwrap() as usize;
let magnitude = 10_usize.pow(index as u32);
let (unit_1, unit_5, unit_10) = match magnitude {
1 => ("I", "V", "X"),
10 => ("X", "L", "C"),
100 => ("C", "D", "M"),
1000 => ("M", "", ""),
_ => ("", "", ""),
};
result += &match digit {
1..=3 => unit_1.repeat(digit),
4 => format!("{unit_5}{unit_1}"),
5 => unit_5.to_string(),
6..=8 => format!("{}{unit_5}", unit_1.repeat(digit - 5)),
9 => format!("{unit_10}{unit_1}"),
_ => continue,
}
}
result.chars().rev().collect()
}

View File

@ -2,6 +2,7 @@ pub mod add_binary;
pub mod excel_sheet_column_number;
pub mod excel_sheet_column_title;
pub mod implement_strstr;
pub mod integer_to_roman;
pub mod isomorphic_strings;
pub mod length_of_last_word;
pub mod longest_common_prefix;

12
tests/integer_to_roman.rs Normal file
View File

@ -0,0 +1,12 @@
use leetcode::integer_to_roman::int_to_roman;
use test_case::test_case;
#[test_case(0, ""; "minimum")]
#[test_case(3999, "MMMCMXCIX"; "maximum")]
#[test_case(1666, "MDCLXVI"; "every character")]
#[test_case(900, "CM"; "with subtracting")]
#[test_case(20, "XX"; "without subtracting")]
fn test_integer_to_roman(input: i32, expected: &str) {
assert_eq!(int_to_roman(input), expected);
}