Skip to content

Commit 4c77e78

Browse files
committed
解けたもの
1 parent bedd48a commit 4c77e78

File tree

2 files changed

+76
-3
lines changed

2 files changed

+76
-3
lines changed

src/integer_to_romen.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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+
}

src/main.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
mod container_with_most_water;
1+
mod integer_to_romen;
2+
23
fn main() {
3-
let height = vec![1, 8, 6, 2, 5, 4, 8, 3, 7];
4-
let result = container_with_most_water::Solution::max_area(height);
4+
let num = 3749;
5+
let result = integer_to_romen::Solution::int_to_roman(num);
56
println!("{:?}", result);
67
}

0 commit comments

Comments
 (0)