// JavaScript
// integer to roman
function convertToRoman(num) {
var decimalValue = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var romanNumeral = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
var ans = "";
for (var i = 0; i < decimalValue.length; i++) {
while (decimalValue[i] <= num) {
num -= decimalValue[i];
ans += romanNumeral[i];
}
}
return ans;
}
convertToRoman(36);
Roman to integer
class Solution {
public int romanToInt(String s) {
int decimalValue[] = {1000, 900, 500, 400, 100, 90, 50, 40,10, 9, 5, 4, 1};
String romanNumerals[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL","X","IX", "V", "IV","I"};
int ans = 0;
int i = s.length() - 1;
while (i >= 0) {
switch(s.charAt(i)) {
case 'I':
ans += 1;
i--;
break;
case 'V':
if (i - 1 >= 0 && s.charAt(i - 1) == 'I') {
ans += 4;
i -= 2;
} else {
ans += 5;
i--;
}
break;
case 'X':
if (i - 1 >= 0 && s.charAt(i - 1) == 'I') {
ans += 9;
i -= 2;
} else {
ans += 10;
i--;
}
break;
case 'L':
if (i - 1 >= 0 && s.charAt(i - 1) == 'X') {
ans += 40;
i -= 2;
} else {
ans += 50;
i--;
}
break;
case 'C':
if (i - 1 >= 0 && s.charAt(i - 1) == 'X') {
ans += 90;
i -= 2;
} else {
ans += 100;
i--;
}
break;
case 'D':
if (i - 1 >= 0 && s.charAt(i - 1) == 'C') {
ans += 400;
i -= 2;
} else {
ans += 500;
i--;
}
break;
case 'M':
if (i - 1 >= 0 && s.charAt(i - 1) == 'C') {
ans += 900;
i -= 2;
} else {
ans += 1000;
i--;
}
break;
}
}
return ans;
}
}