Skip to content

Commit 2d0d4ec

Browse files
committed
Create: 0012-integer-to-roman.rs / .ts
1 parent ee7a3bc commit 2d0d4ec

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: rust/0012-integer-to-roman.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
impl Solution {
2+
pub fn int_to_roman(num: i32) -> String {
3+
let int = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
4+
let roman = [
5+
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I",
6+
];
7+
let mut result = String::new();
8+
let mut num = num;
9+
10+
for i in 0..13 {
11+
if num / int[i] > 0 {
12+
let count = num / int[i];
13+
result.push_str(&roman[i].repeat(count as usize));
14+
num %= int[i];
15+
}
16+
}
17+
18+
result
19+
}
20+
}

Diff for: typescript/0012-integer-to-roman.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function intToRoman(num: number): string {
2+
const map = {
3+
M: 1000,
4+
CM: 900,
5+
D: 500,
6+
CD: 400,
7+
C: 100,
8+
XC: 90,
9+
L: 50,
10+
XL: 40,
11+
X: 10,
12+
IX: 9,
13+
V: 5,
14+
IV: 4,
15+
I: 1,
16+
};
17+
18+
let result = '';
19+
20+
for (let key in map) {
21+
const repeatCounter = Math.floor(num / map[key]);
22+
23+
if (repeatCounter !== 0) result += key.repeat(repeatCounter);
24+
25+
num %= map[key];
26+
27+
if (num == 0) return result;
28+
}
29+
30+
return result;
31+
}

0 commit comments

Comments
 (0)