[leetcode] the day of leetcode

Time:2021-5-11

Topic content

Roman numerals contain the following seven characters:   I,   V,   X,   L,C,D   and   M。

character numerical value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, the Roman numeral 2 is written as   II  , That is, two parallel ones. 12 writing and doing   XII  , mean   X  +  II  。 27 writing and doing    27. That is to say   XX  +  V  +  II  。

Usually, the small numbers in Roman numerals are to the right of the large numbers. But there are some special cases, such as 4 not to write   IIII, but   IV。 The number 1 is on the left side of the number 5, which is equal to the number 4 obtained by subtracting the decimal 1 from the large number 5. Similarly, the number 9 denotes   IX。 This special rule only applies to the following six cases:

  • I   Can be placed in   V  ( 5) And   X  ( 10) To the left of, to represent 4 and 9.
  • X   Can be placed in   L  ( 50) and   C  ( To the left of (100) for 40 and   90。
  • C   Can be placed in   D  ( 500) and   M  ( 1000) to the left   400 and   900。

Given a Roman number, convert it to an integer. Make sure the input is within 1   To 3999.

Examples   1:

Input:  " III"
Output: 3

Examples   2:

Input:  " IV"
Output: 4

Examples   3:

Input:  " IX"
Output: 9

Examples   4:

Input:  " LVIII"
Output: 58
Explanation: l = 50, v = 5, III = 3

Examples   5:

Input:  " MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4

Thinking of solving problems

If the behavior of ICX preposition is not considered, the conversion can be completed by adding directly. However, according to the observation, it can be seen that no matter cm, IV or other subtraction cases, the first letter is smaller than the last letter, and then the total value is the sum of all the letters, minus twice the first letter. For example, IV, the sum of letters is 6, but the actual value is 6 – 2 = 4. Therefore, the code can be written according to this feature

The code is

fn roman_to_int(s: String) -> i32 {
    let mut num: i32 = 0;

    let mut val: i32 = 0;
    let mut last: i32 = 0;

    for i in s.chars() {
        match i {
            'M' => val = 1000,
            'D' => val = 500,
            'C' => val = 100,
            'L' => val = 50,
            'X' => val = 10,
            'V' => val = 5,
            'I' => val = 1,
            _ => val = 0,
        }

        if val > last {
            num -= last * 2;
        }
        last = val;
        num += val;
    }

    return num;
}

#[test]
fn test_roman_to_int() {
    assert_eq!(roman_to_int(String::from("LVIII")), 58);
}