-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13-Roman_To_Integer.rs
More file actions
50 lines (45 loc) · 1.18 KB
/
Copy path13-Roman_To_Integer.rs
File metadata and controls
50 lines (45 loc) · 1.18 KB
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
struct Solution;
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let bytes = s.as_bytes();
let mut sum: i32 = 0;
for i in 0..bytes.len() {
let val = match bytes[i] {
b'I' => 1,
b'V' => 5,
b'X' => 10,
b'L' => 50,
b'C' => 100,
b'D' => 500,
b'M' => 1000,
_ => 0,
};
if i + 1 < bytes.len() {
let next = match bytes[i + 1] {
b'I' => 1,
b'V' => 5,
b'X' => 10,
b'L' => 50,
b'C' => 100,
b'D' => 500,
b'M' => 1000,
_ => 0,
};
if val < next {
sum -= val;
} else {
sum += val;
}
} else {
sum += val;
}
}
sum
}
}
fn main() {
let tests = vec!["III", "LVIII", "MCMXCIV"];
for t in tests {
println!("{} -> {}", t, Solution::roman_to_int(t.to_string()));
}
}