leetcode_rust/
integer_to_roman.rs1#![allow(dead_code)]
2
3pub fn int_to_roman(num: i32) -> String {
4 let mut res = String::from("");
5 let mut num = num;
6 while num >= 1000 {
7 res.push('M');
8 num -= 1000;
9 }
10 if num >= 900 {
11 res.push_str("CM");
12 num -= 900;
13 }
14 if num >= 500 {
15 res.push('D');
16 num -= 500;
17 }
18 if num >= 400 {
19 res.push_str("CD");
20 num -= 400;
21 }
22 while num >= 100 {
23 res.push('C');
24 num -= 100;
25 }
26 if num >= 90 {
27 res.push_str("XC");
28 num -= 90;
29 }
30 if num >= 50 {
31 res.push('L');
32 num -= 50;
33 }
34 if num >= 40 {
35 res.push_str("XL");
36 num -= 40;
37 }
38 while num >= 10 {
39 res.push('X');
40 num -= 10;
41 }
42 if num >= 9 {
43 res.push_str("IX");
44 num -= 90;
45 }
46 if num >= 5 {
47 res.push('V');
48 num -= 5;
49 }
50 if num >= 4 {
51 res.push_str("IV");
52 num -= 4;
53 }
54 while num >= 1 {
55 res.push('I');
56 num -= 1;
57 }
58
59 res
60}
61
62pub fn int_to_roman2(num: i32) -> String {
63 let romans = vec![
64 "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I",
65 ];
66 let integers = vec![1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
67 let mut res = String::from("");
68 let mut num = num;
69 for (i, &val) in integers.iter().enumerate() {
70 while num >= val {
71 num -= val;
72 res.push_str(romans[i])
73 }
74 }
75
76 res
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn test1() {
85 assert_eq!(int_to_roman(1994), String::from("MCMXCIV"));
86 }
87
88 #[test]
89 fn test2() {
90 assert_eq!(int_to_roman2(1994), String::from("MCMXCIV"));
91 }
92}