-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0012_integer_roman.rs
52 lines (45 loc) · 1.15 KB
/
s0012_integer_roman.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#![allow(unused)]
pub struct Solution {}
impl Solution {
// O(1) O(1)
pub fn int_to_roman(mut num: i32) -> String {
let digits = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
];
let mut ans = "".to_string();
for &(val, sym) in digits.iter() {
if num < 0 {
break;
}
while val <= num {
num -= val;
ans.push_str(sym);
}
}
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_12() {
assert_eq!(Solution::int_to_roman(3), "III".to_string());
assert_eq!(Solution::int_to_roman(4), "IV".to_string());
assert_eq!(Solution::int_to_roman(9), "IX".to_string());
assert_eq!(Solution::int_to_roman(58), "LVIII".to_string());
assert_eq!(Solution::int_to_roman(1994), "MCMXCIV".to_string());
}
}