Skip to content

Commit

Permalink
Create: 0012-integer-to-roman.rs / .ts
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 4, 2023
1 parent ee7a3bc commit 2d0d4ec
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions rust/0012-integer-to-roman.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
impl Solution {
pub fn int_to_roman(num: i32) -> String {
let int = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let roman = [
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I",
];
let mut result = String::new();
let mut num = num;

for i in 0..13 {
if num / int[i] > 0 {
let count = num / int[i];
result.push_str(&roman[i].repeat(count as usize));
num %= int[i];
}
}

result
}
}
31 changes: 31 additions & 0 deletions typescript/0012-integer-to-roman.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function intToRoman(num: number): string {
const map = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};

let result = '';

for (let key in map) {
const repeatCounter = Math.floor(num / map[key]);

if (repeatCounter !== 0) result += key.repeat(repeatCounter);

num %= map[key];

if (num == 0) return result;
}

return result;
}

0 comments on commit 2d0d4ec

Please sign in to comment.