-
Notifications
You must be signed in to change notification settings - Fork 10
/
int_to_roman.rs
82 lines (77 loc) · 1.97 KB
/
int_to_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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*! https://leetcode.com/problems/integer-to-roman/
& https://leetcode.com/problems/roman-to-integer/
# 贪心: 每次尽可能匹配数值更大的罗马字母
例如M是最大的罗马字母,如果num=9000,则将M重复9次
```python
def in_to_roman(num: int) -> str:
ret = ''
for (integer, roman) in int_to_roman:
if num >= integer:
count, num = divmod(num, integer)
ret += roman * count
return ret
```
def roman_to_int(s: str) -> int:
ret = 0
# 用HashMap可能会快点
for (integer, roman) in int_to_roman:
n = len(roman)
while s.startswith(roman):
ret += integer
s = s[n:]
return ret
*/
const INT_TO_ROMAN: [(i32, &[u8]); 13] = [
(1000, b"M"),
(900, b"CM"),
(500, b"D"),
(400, b"CD"),
(100, b"C"),
(90, b"XC"),
(50, b"L"),
(40, b"XL"),
(10, b"X"),
(9, b"IX"),
(5, b"V"),
(4, b"IV"),
(1, b"I"),
];
fn int_to_roman(mut num: i32) -> String {
let mut ret = Vec::new();
for &(int, roman) in &INT_TO_ROMAN {
// while num >= int {
// ret.extend_from_slice(roman);
// num -= int;
// }
if num >= int {
ret.extend(roman.repeat((num / int) as usize));
num %= int;
}
}
unsafe { String::from_utf8_unchecked(ret) }
}
fn roman_to_int(s: String) -> i32 {
let s = s.into_bytes();
let len = s.len();
let mut i = 0;
let mut ret = 0;
for &(int, roman) in &INT_TO_ROMAN {
let roman_len = roman.len();
while s[i..].starts_with(roman) {
ret += int;
i += roman_len;
if i >= len {
return ret;
}
}
}
unreachable!()
}
#[test]
fn test() {
const TEST_CASES: [(&str, i32); 2] = [("LVIII", 58), ("MCMXCIV", 1994)];
for &(roman, int) in &TEST_CASES {
assert_eq!(int_to_roman(int), roman);
assert_eq!(roman_to_int(roman.to_string()), int);
}
}