leetcode_rust/problems/p000_0xx/p000_013.rs
1//! # Description
2//!
3//! Roman numerals are represented by seven different symbols: `I`, `V`, `X`,
4//! `L`, `C`, `D` and `M`.
5//!
6//! ```plain
7//! Symbol Value
8//! I 1
9//! V 5
10//! X 10
11//! L 50
12//! C 100
13//! D 500
14//! M 1000
15//! ```
16//!
17//! For example, `2` is written as `II` in Roman numeral, just two ones added
18//! together. `12` is written as `XII`, which is simply `X` + `II`. The number
19//! `27` is written as `XXVII`, which is `XX` + `V` + `II`.
20//!
21//! Roman numerals are usually written largest to smallest from left to right.
22//! However, the numeral for four is not `IIII`. Instead, the number four is
23//! written as `IV`. Because the one is before the five we subtract it making
24//! four. The same principle applies to the number nine, which is written as
25//! `IX`. There are six instances where subtraction is used:
26//!
27//! - `I` can be placed before `V` (`5`) and `X` (`10`) to make `4` and `9`.
28//! - `X` can be placed before `L` (`50`) and `C` (`100`) to make `40` and `90`.
29//! - `C` can be placed before `D` (`500`) and `M` (`1000`) to make `400` and `900`.
30//!
31//! Given a roman numeral, convert it to an integer.
32//!
33//!
34//!
35//! Example 1:
36//!
37//! ```plain
38//! Input: s = "III"
39//! Output: 3
40//! Explanation: III = 3.
41//! ```
42//!
43//! Example 2:
44//!
45//! ```plain
46//! Input: s = "LVIII"
47//! Output: 58
48//! Explanation: L = 50, V= 5, III = 3.
49//! ```
50//!
51//! Example 3:
52//!
53//! ```plain
54//! Input: s = "MCMXCIV"
55//! Output: 1994
56//! Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
57//! ```
58//!
59//! Constraints:
60//!
61//! - `1 $\leqslant$ s.length $\leqslant$ 15`
62//! - `s` contains only the characters ('`I`', '`V`', '`X`', '`L`', '`C`',
63//! '`D`', '`M`').
64//! - It is guaranteed that `s` is a valid roman numeral in the range `[1, 3999]`.
65//!
66//! Sources: <https://leetcode.com/problems/roman-to-integer/description/>
67
68////////////////////////////////////////////////////////////////////////////////
69
70/// Integer to Roman
71///
72/// # Arguments
73/// * `s` - input string
74pub fn roman_to_int(s: String) -> i32 {
75 let mut val = 0;
76 let mut last_val = 0;
77 let mut temp_digit = 0;
78
79 for ch in s.as_bytes().iter() {
80 let this_val = match *ch {
81 b'I' => 1,
82 b'V' => 5,
83 b'X' => 10,
84 b'L' => 50,
85 b'C' => 100,
86 b'D' => 500,
87 b'M' => 1000,
88 _ => 0,
89 };
90 if last_val == 0 {
91 temp_digit = this_val;
92 } else if this_val == last_val {
93 temp_digit += this_val;
94 } else if this_val < last_val {
95 val += temp_digit;
96 temp_digit = this_val;
97 } else {
98 val += this_val - temp_digit;
99 temp_digit = 0;
100 }
101 last_val = this_val;
102 }
103 val += temp_digit;
104 val
105}