###### tags: `leetcode` `rust` # ローマ数字を整数値にする - https://leetcode.com/problems/roman-to-integer/ ローマ数字を整数値にするプログラムを Rust で書く。 ### 問題 ローマ数字の文字列 s を整数値にする。 I, V, X, L, C, D, M の 7 つの文字が対象。 | Symbol | Value | |:------ |:----- | | I | 1 | | V | 5 | | X | 10 | | L | 50 | | C | 100 | | D | 500 | | M | 1000 | ```rust= s = "III" // 3 s = "LVIII" // 58 s = "MCMXCIV" // 1994 ``` ### 初期コード roman_to_int 関数を完成させる。 ```rust= impl Solution { pub fn roman_to_int(s: String) -> i32 { } } ``` ### アルゴリズム - 左側に置かれる I, X, C について、右側に置く形に置換する - 置換後の文字列を 1バイトずつ読み込んで、該当する値を足していく ### 完成したコード ```rust= impl Solution { pub fn roman_to_int(s: String) -> i32 { let mut str = s; str = str.replace("IV", "IIII"); str = str.replace("IX", "VIIII"); str = str.replace("XL", "XXXX"); str = str.replace("XC", "LXXXX"); str = str.replace("CD", "CCCC"); str = str.replace("CM", "DCCCC"); let mut num = 0; for sb in str.bytes().rev() { //println!("{:?}", sb); match sb { b'I' => num = num + 1, b'V' => num = num + 5, b'X' => num = num + 10, b'L' => num = num + 50, b'C' => num = num + 100, b'D' => num = num + 500, b'M' => num = num + 1000, _ => { } } } num } } ```