-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13-Roman_to_Integer.rs
More file actions
41 lines (38 loc) · 1 KB
/
Copy path13-Roman_to_Integer.rs
File metadata and controls
41 lines (38 loc) · 1 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
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
}
}