-
Notifications
You must be signed in to change notification settings - Fork 81
/
toRomanNum.js
43 lines (40 loc) · 881 Bytes
/
toRomanNum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// to run: node toRomanNum.js
const toRomanNum = num => {
const romanObj = {
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I"
};
const keys = Object.keys(romanObj).sort((a, b) => b - a);
let output = "";
const innerLoop = () => {
for (var i = 0; i < keys.length; i++) {
if (num >= keys[i]) {
output += romanObj[keys[i]];
num -= keys[i];
return;
}
}
};
while (num > 0) {
innerLoop();
}
return output;
};
console.log(toRomanNum(33)); // XXXIII
// console.log(toRomanNum(41)); // XLI
// console.log(toRomanNum(76)); // LXXVI
// console.log(toRomanNum(376)); //CCCLXXVI
// console.log(toRomanNum(0)); // ""
// console.log(toRomanNum(999)); // CMXCIX
// console.log(toRomanNum(1000)); // M