1function convertToRoman(num) {
2var numeral = "";
3 var arr = [
4 {number:1, roman: "I"},
5 {number:4, roman: "IV"},
6 {number:5, roman: "V"},
7 {number:9, roman: "IX"},
8 {number:10, roman: "X"},
9 {number:40, roman: "XL"},
10 {number:50, roman: "L"},
11 {number:90, roman: "XC"},
12 {number:100, roman: "C"},
13 {number:400, roman: "CD"},
14 {number:500, roman: "D"},
15 {number:900, roman: "CM"},
16 {number:1000, roman: "M"}
17 ]
18 while(num > 0){
19 var searching = arr.filter(function(myArr){
20 if(myArr.number <= num){
21 return myArr.number
22 }
23 })
24 var latest = searching.pop()
25 var full = Math.floor(num / latest.number)
26 for(let i = 0; i<full; i++){
27 numeral +=latest.roman
28 }
29 num = num % latest.number
30 }
31 return numeral
32}
33
34console.log(convertToRoman(36));
1function roman_to_Int(str1) {
2if(str1 == null) return -1;
3var num = char_to_int(str1.charAt(0));
4var pre, curr;
5
6for(var i = 1; i < str1.length; i++){
7curr = char_to_int(str1.charAt(i));
8pre = char_to_int(str1.charAt(i-1));
9if(curr <= pre){
10num += curr;
11} else {
12num = num - pre*2 + curr;
13}
14}
15
16return num;
17}
18
19function char_to_int(c){
20switch (c){
21case 'I': return 1;
22case 'V': return 5;
23case 'X': return 10;
24case 'L': return 50;
25case 'C': return 100;
26case 'D': return 500;
27case 'M': return 1000;
28default: return -1;
29}
30}
31console.log(roman_to_Int('XXVI'));
32console.log(roman_to_Int('CI'));
1class Solution {
2public:
3 int romanNumber(char n)
4 {
5 switch (n)
6 {
7 case 'I':
8 return (1);
9 case 'V':
10 return (5);
11 case 'X':
12 return (10);
13 case 'L':
14 return (50);
15 case 'C':
16 return (100);
17 case 'D':
18 return (500);
19 case 'M':
20 return (1000);
21 default:
22 return (0);
23
24 }
25 return (0);
26 }
27 int romanToInt(string s)
28 {
29 int len = s.size();
30 int ans = romanNumber(s[0]);
31 for(int i=1;i<len;i++)
32 {
33 int prev = romanNumber(s[i-1]);
34 int current = romanNumber(s[i]);
35 if(prev>=current)
36 {
37 ans += current;
38 }
39 else
40 {
41 ans -= prev;
42 current -= prev;
43 ans += current;
44 }
45 }
46 return ans;
47 }
48};