You should be proud!! It’s shorter and easy to read than most I’ve seen

# Roman Numeral Converter Challenge

**kevinSmith**#68

Yes, it was a tough one. Looks good.

I might have used a *switch* statement instead of the *if-else* chain, but that’s more style than function.

**randelldawson**#70

@cacauzen - I really liked your unique solution and I took your concept of how you created your arrays and with the exception of the thousands place, I was able to use the values you used. Then I created a for loop to iterate through my two dimensional array that was based on your solution. What do you think of my solution which was inspired by yours?

```
function convertToRoman(num) {
var conversions = [
["","I","II","III","IV","V","VI","VII","VIII","IX"],
["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
["", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
["",""]
];
var arr = num.toString().split("");
var thou = "M".repeat(arr.length>3 ? arr[0]:0);
for (var i=0,j=arr.length-1;j>=0;i++) {
arr[i] = conversions[j--][arr[i]];
}
return thou+=arr.join("");
}
```

**cacauzen**#71

@rmdawson71 I think it’s genius! I’ll probably delete my solution and try to replicate yours, since it’s much compact and elegant. Great job

**randelldawson**#72

I think it is easier to go from Roman Numeral to integer. I created this from a challenge on a different website:

```
var romanToInteger = function(s) {
var conversions = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};
for (var integer=0, prev=0, i = 0; i < s.length; i++) {
var curr = conversions[s[i]];
integer += (prev < curr) ? curr - 2*prev : curr;
prev = curr;
}
return integer;
}
```

**paintingfire**#73

When I started working on this I had a series of if statements… it was ridiculous. Here’s what I finally came up with. It’s amazing to see the number of ways people have solved this challenge!

```
var roman = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'];
var arabic = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
function convertToRoman(num) {
var result = [];
for (i = 0; i < roman.length; i++) {
while ((num - arabic[i]) >= 0) {
result.push(roman[i]);
num -= arabic[i];
}
}
return result.join("");
}
```

**pablopaul**#74

I think @paintingfire’s solution is great. Very clear, fast, and concise.

In this situation, where there are clear limits to the range (0 to 3999) and ways in which the values can be expressed, it makes more sense to use smart arrays than complicated formulas. Nevertheless, I took the formula approach.

I read on StackOverflow that if-then statements are faster than case-switch statements when dealing with values that are not exact (i.e. > 4, < 4), so I opted for the if-then approach.

I’m also impressed with all the different solutions others came up with!

```
function convertToRoman(num) {
if (!(num > 0 && num < 4000)) return false; // just to be safe
var numStr = num.toString();
var x = (numStr.length - 1) * 2; // roman numeral array index
var rnArr = ["I", "V", "X", "L", "C", "D", "M"];
var rnStr = "";
for (var i = 0; i < numStr.length; i++, x-=2) {
var digit = parseInt(numStr.charAt(i), 10);
if (digit == 9) {
rnStr += rnArr[x] + rnArr[x + 2];
} else if (digit > 4) {
rnStr += rnArr[x + 1];
rnStr += Array(digit - 4).join(rnArr[x]);
} else if (digit == 4) {
rnStr += rnArr[x] + rnArr[x + 1];
} else {
rnStr += Array(digit + 1).join(rnArr[x]);
}
}
return rnStr;
}
```

**DanCouper**#76

```
const numeralGroups = [
['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
['', 'M', 'MM', 'MMM'],
]
function convertToRoman(number) {
return number.toString()
.split('')
.map(char => parseInt(char, 10))
.reverse()
.map((v, i) => numeralGroups[i][v])
.reverse()
.join('')
}
```

So For say 1234. Convert to an array of digits. Work backwards, converting ones, then tens, then hundreds, then thousands. [4, 3, 2, 1]. so:

- 4 is at index 0 - look in the first subarray of numerals, at the character at index 4, which is “IV” (this is why there’s an empty string at the start of each group).
- 3 is at index 1 - look in the second subarray of numerals, at character at index 3, which is “XXX”
- 2 is at index 2 - look in the third subarray of numerals, at character at index 2, which is “CC”
- 1 is at index 3 - look in the fourth subarray of numerals, at character at index 1, which is “M”

This results in [“IV”,“XXX”,“CC”,“M”], which is backward, so reverse and join to give “MCCXXIV”

**pzaj2**#77

I just thought I’d share mine as well

```
var romans = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M',
};
function convertToRoman(num) {
if(num <= 0) {
return 'N';
}
var keys = Object.keys(romans).reverse();
var m = keys.splice(0, 1)[0];
var roman = '';
while(num > 0) {
if(num >= m) {
roman += romans[m];
num -= m;
} else {
m = keys.splice(0, 1)[0];
}
}
return roman;
}
```

**tmpbit**#78

In my solution I didn’t convert a number to strings, instead I used some maths

In theory it converts numbers up to 1 million, but then some letters needs a dash over them.

I thought I was cheating using arrays, but it seemed so easy using them that I decided to use them.

Below is my code:

```
function convertToRoman(num) {
var pow = 0;
var mod = 0;
var res = [];
function getLetters(pow) {
var arr;
switch (pow) {
case 0:
arr = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
break;
case 1:
arr = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
break;
case 2:
arr = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
break;
case 3:
arr = ["M", "MM", "MMM", "MV", "V", "VM", "VMM", "VMMM", "MX"];
break;
}
return arr;
}
while (num >= 10) {
mod = num % 10; //getting the last digit as a mod
num = Math.trunc(num / 10); //and 'deleting' the last digit from the num
var tmp = getLetters(pow)[mod-1]; //getting the corresponding letters from appropriate array
if (tmp !== undefined) { //if it wasn't possible do nothing
res.unshift(tmp); //otherwise put on front of res array
}
if (pow > 3) { //it alows taking letters from [1] array (instead of [4])
pow -= 3; //and loop in that way over the last 3 arrays
} else { //but no dash over the symbols... :(
pow++;
}
}
res.unshift(getLetters(pow)[num-1]);//sorting out the last digit (if num < 10)
res = res.join(""); //joining all letters from res array
return res;
}
convertToRoman(36);
```

**Gh05d**#79

I liked my solution until I realized that I had to replace values like IIII with IV. I think that is the precise moment when I began coding shit. I was able to pass all the tests, but I am not sure whether this is still a valid solution. Any feedback would be welcome:

```
function convertToRoman(num) {
var alphabet = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
var feedRecursive = [ 1, 5, 10, 50, 100, 500, 1000];
function recursiveConversion(value, n) {
if(value % feedRecursive[n] == 0) {
for (var i = 0; i < Math.trunc(value / feedRecursive[n]); i++) {
erg.push(Object.keys(alphabet)[n]);
}
return console.log(value);
}
if(Math.trunc(value / feedRecursive[n]) != 0) {
for (var i = 0; i < Math.trunc(value / feedRecursive[n]); i++) {
erg.push(Object.keys(alphabet)[n]);
}
value -= (Math.trunc(value / feedRecursive[n])) * feedRecursive[n];
}
console.log(n, value)
return recursiveConversion(value, n-1);
}
var erg = [];
recursiveConversion(num, Object.keys(alphabet).length - 1);
ergString = erg.join("").replace(/(IIIIV)|(IIII)\b/g, "IV").replace(/(VIIII)|(IIIIX)|(VIV)/g, "IX").replace(/(XXXXL)|(XXXX)/g, "XL").replace(/(XXXXC)|(LXXXX)|(LXL)/g,"XC").replace(/(CCCCD)/g, "CD").replace(/(CCCCM)|(DCCCC)/g, "CM");
console.log(ergString);
return ergString;
}
convertToRoman(3999);
```

**stefanlagrange**#80

Thanks! This solution looks very elegant.

The arrays also provide a quick way to lookup values in the future.

**mtso**#81

Not mine, but I remember coming across this one:

leetcode constrains the input Integer to between 1 and 3999.

```
public static String intToRoman(int num) {
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
```

Like tmpbit’s conceptually

**afixoftrix**#83

Mine is prolly the worst one on here because of my egregious logic. I even have nested loops. I also didn’t want to hard code 4s and 9s. I felt like that took away from the challenge. There are much better ways to write it.

```
function convertToRoman(num) {
var numerals = {
"1": "I",
"5": "V",
"10": "X",
"50": "L",
"100": "C",
"500": "D",
"1000": "M"
};
//var numer = [1,5,10,50,100,500,1000], arr = [],
var counter = [], romanNumeral = [], factorArray = [] ;
function romanFactors(num){
var arry = [], numer = [1,5,10,50,100,500,1000];
for(var i = 0; numer[i]<=num; i++ ){
arry.push(numer[i]);
}
factorArray = arry.reverse();
//console.log(factorArray);
return factorArray;
}
romanFactors(num).filter(function (item){
if ((num/item)>=1){
var modulus = num%item;
var factor = (num-modulus)/item;
counter.push(factor);
//console.log(counter);
num = num - (factor*item);
//console.log(num);
return factor;
}
else {
counter.push(0);
return 0;
}
});
for (var j = 0; j < factorArray.length; j++){
for (var i = 0; i < counter[j]; i++){
if(counter[j]==4){
if (((counter[j-1]) === 0)||((counter[j-1])===undefined)){
//console.log((factorArray[j]));
//console.log(numerals[factorArray[j]*5]);
romanNumeral.push(numerals[factorArray[j]], numerals[(factorArray[j]*5)]);
break;
}
else{
romanNumeral.pop();
//console.log((factorArray[j]));
//console.log(numerals[factorArray[j]*10]);
romanNumeral.push(numerals[factorArray[j]], numerals[(factorArray[j]*10)]);
break;
}
}
else{
//console.log(numerals[factorArray[j]]);
romanNumeral.push(numerals[factorArray[j]]);
}
}
}
return romanNumeral.join("");
}
convertToRoman(891);
```

**Gh05d**#84

I feel you. I also allways shiver when using nested loops, but I guess at this stage of web development experience, it’s okay. The 4’s and 9’s nearly broke me, and I guess I cheated out by using regex, but I couldn’t look at that challenge anymore ^^

**jwolfjim**#85

Mine is pretty ugly but works. I would like to see some performance evaluations about my code versus other codes. I look at other peoples and think they may be a little more clever but… I am happy to break through this one. I may add a for loop to clean up some of the repetitive code. It does not get much more basic than this but I am still happy with it.

```
function convertToRoman(num) {
var p = num;
var dig = p.toString();
var ans = "";
var ans1 = "";
var ans2 = "";
var ans3 = "";
//return dig;
var y = dig.slice(-1);
y = parseInt(y);
switch (y) {
case 0:
ans = "";
break;
case 1:
ans = "I";
break;
case 2:
ans = "II";
break;
case 3:
ans = "III";
break;
case 4:
ans = "IV";
break;
case 5:
ans = "V";
break;
case 6:
ans = "VI";
break;
case 7:
ans = "VII";
break;
case 8:
ans = "VIII";
break;
case 9:
ans = "IX";
break;
default:
ans = '';
}
var z = dig.slice(-2, -1);
z = parseInt(z);
//return z;
switch (z) {
case 0:
ans1 = "";
break;
case 1:
ans1 = "X";
break;
case 2:
ans1 = "XX";
break;
case 3:
ans1 = "XXX";
break;
case 4:
ans1 = "XL";
break;
case 5:
ans1 = "L";
break;
case 6:
ans1 = "LX";
break;
case 7:
ans1 = "LXX";
break;
case 8:
ans1 = "LXXX";
break;
case 9:
ans1 = "XC";
break;
default:
ans1 = '';
}
var z1 = dig.slice(-3, -2);
z1 = parseInt(z1);
//return z;
switch (z1) {
case 0:
ans2 = "";
break;
case 1:
ans2 = "C";
break;
case 2:
ans2 = "CC";
break;
case 3:
ans2 = "CCC";
break;
case 4:
ans2 = "CD";
break;
case 5:
ans2 = "D";
break;
case 6:
ans2 = "DC";
break;
case 7:
ans2 = "DCC";
break;
case 8:
ans2 = "DCCC";
break;
case 9:
ans2 = "CM";
break;
default:
ans2 = '';
}
var z2 = dig.slice(-4, -3);
z2 = parseInt(z2);
//return z;
switch (z2) {
case 0:
ans3 = "";
break;
case 1:
ans3 = "M";
break;
case 2:
ans3 = "MM";
break;
case 3:
ans3 = "MMM";
break;
default:
ans3 = '';
}
return ans3 + ans2 + ans1 + ans;
}
convertToRoman(389);
```

**AlonsoGD**#86

Oh god.

This challenge almost crushed me… I was literally desperate because the algorithms that came to my mind naturally were super complicated (I guess my mind is broken… I knew but… xD) finally I had to have a look to some of the solutions of other campers and after that tried to make my own.

This is what I did, I feel very proud but really had a bad time with this challenge.