|
| 1 | +pub struct Solution {} |
| 2 | +impl Solution { |
| 3 | + pub fn int_to_roman(num: i32) -> String { |
| 4 | + // 制約が1~3999なので4000以降は考えなくて良い |
| 5 | + struct RomanSource { |
| 6 | + thousand: usize, |
| 7 | + hundred: usize, |
| 8 | + ten: usize, |
| 9 | + one: usize, |
| 10 | + } |
| 11 | + |
| 12 | + // まずは1000, 100, 10, 1の位を取得 |
| 13 | + let roman_source = RomanSource { |
| 14 | + thousand: (num / 1000) as usize, |
| 15 | + hundred: ((num % 1000) / 100) as usize, |
| 16 | + ten: ((num % 100) / 10) as usize, |
| 17 | + one: (num % 10) as usize, |
| 18 | + }; |
| 19 | + |
| 20 | + // マッチ式で処理 |
| 21 | + fn roman_num( |
| 22 | + num: usize, |
| 23 | + alphabet_one: char, |
| 24 | + alphabet_five: char, |
| 25 | + alphabet_ten: char, |
| 26 | + ) -> String { |
| 27 | + match num { |
| 28 | + 0 => "".to_string(), |
| 29 | + 1..=3 => alphabet_one.to_string().repeat(num), |
| 30 | + 4 => format!("{}{}", alphabet_one, alphabet_five), |
| 31 | + 5 => alphabet_five.to_string(), |
| 32 | + 6..=8 => format!( |
| 33 | + "{}{}", |
| 34 | + alphabet_five, |
| 35 | + alphabet_one.to_string().repeat(num - 5) |
| 36 | + ), |
| 37 | + 9 => format!("{}{}", alphabet_one, alphabet_ten), |
| 38 | + _ => "".to_string(), |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // それぞれの位をローマ数字に変換 |
| 43 | + let thousand = roman_num(roman_source.thousand, 'M', ' ', ' '); |
| 44 | + let hundred = roman_num(roman_source.hundred, 'C', 'D', 'M'); |
| 45 | + let ten = roman_num(roman_source.ten, 'X', 'L', 'C'); |
| 46 | + let one = roman_num(roman_source.one, 'I', 'V', 'X'); |
| 47 | + |
| 48 | + // 連結して返す |
| 49 | + format!("{}{}{}{}", thousand, hundred, ten, one) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +#[cfg(test)] |
| 54 | +mod tests { |
| 55 | + use super::*; |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn test_1() { |
| 59 | + let num = 3749; |
| 60 | + assert_eq!(Solution::int_to_roman(num), "MMMDCCXLIX".to_string()); |
| 61 | + } |
| 62 | + #[test] |
| 63 | + fn test_2() { |
| 64 | + let num = 58; |
| 65 | + assert_eq!(Solution::int_to_roman(num), "LVIII".to_string()); |
| 66 | + } |
| 67 | + #[test] |
| 68 | + fn test_3() { |
| 69 | + let num = 1994; |
| 70 | + assert_eq!(Solution::int_to_roman(num), "MCMXCIV".to_string()); |
| 71 | + } |
| 72 | +} |
0 commit comments