13. Roman to Integer Easy
1/**
2 * [13] Roman to Integer
3 *
4 * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
5 *
6 * Symbol Value
7 * I 1
8 * V 5
9 * X 10
10 * L 50
11 * C 100
12 * D 500
13 * M 1000
14 * For example, 2 is written as II in Roman numeral, just two one's
15 * added together. 12 is written as XII, which is simply X + II.
16 * The number 27 is written as XXVII, which is XX + V + II.
17 * Roman numerals are usually written largest to smallest from left
18 * to right. However, the numeral for four is not IIII. Instead,
19 * the number four is written as IV. Because the one is before the
20 * five we subtract it making four. The same principle applies to
21 * the number nine, which is written as IX. There are six instances
22 * where subtraction is used:
23 *
24 * I can be placed before V (5) and X (10) to make 4 and 9.
25 * X can be placed before L (50) and C (100) to make 40 and 90.
26 * C can be placed before D (500) and M (1000) to make 400 and 900.
27 *
28 * Given a roman numeral, convert it to an integer.
29 *
30 * Example 1:
31 *
32 * Input: s = "III"
33 * Output: 3
34 *
35 * Example 2:
36 *
37 * Input: s = "IV"
38 * Output: 4
39 *
40 * Example 3:
41 *
42 * Input: s = "IX"
43 * Output: 9
44 *
45 * Example 4:
46 *
47 * Input: s = "LVIII"
48 * Output: 58
49 * Explanation: L = 50, V= 5, III = 3.
50 *
51 * Example 5:
52 *
53 * Input: s = "MCMXCIV"
54 * Output: 1994
55 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
56 *
57 *
58 * Constraints:
59 *
60 * 1 <= s.length <= 15
61 * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
62 * It is guaranteed that s is a valid roman numeral in the range [1, 3999].
63 *
64 */
65pub struct Solution {}
66
67// problem: https://leetcode.com/problems/roman-to-integer/
68// discuss: https://leetcode.com/problems/roman-to-integer/discuss/?currentPage=1&orderBy=most_votes&query=
69
70// submission codes start here
71use std::collections::HashMap;
72impl Solution {
73 pub fn roman_to_int(s: String) -> i32 {
74 let map: HashMap<char, i32> = [
75 ('I', 1),
76 ('V', 5),
77 ('X', 10),
78 ('L', 50),
79 ('C', 100),
80 ('D', 500),
81 ('M', 1000),
82 ]
83 .iter()
84 .cloned()
85 .collect();
86
87 let mut result = 0;
88 let chs: Vec<char> = s.chars().collect();
89 for (i, c) in chs.iter().enumerate() {
90 result += map.get(&c).unwrap();
91 if i != 0 && map.get(&chs[i - 1]).unwrap() < map.get(&chs[i]).unwrap() {
92 result -= 2 * map.get(&chs[i - 1]).unwrap();
93 }
94 }
95 result
96 }
97}
98
99// submission codes end
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 #[test]
106 fn test_13() {
107 assert_eq!(Solution::roman_to_int("IX".into()), 9);
108 assert_eq!(Solution::roman_to_int("MCMXCIV".into()), 1994);
109 }
110}
111
Back
© 2025 bowen.ge All Rights Reserved.