forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create: 0012-integer-to-roman.rs / .ts
- Loading branch information
1 parent
ee7a3bc
commit 2d0d4ec
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |