Skip to content

Instantly share code, notes, and snippets.

@basekays
Created June 20, 2018 00:54
Show Gist options
  • Select an option

  • Save basekays/69cc9df59dcc9f8da5544a4ebf8ce26c to your computer and use it in GitHub Desktop.

Select an option

Save basekays/69cc9df59dcc9f8da5544a4ebf8ce26c to your computer and use it in GitHub Desktop.
//input string
//output number
// I can be placed before V (5) and X (10) to make 4 and 9.
// X can be placed before L (50) and C (100) to make 40 and 90.
// C can be placed before D (500) and M (1000) to make 400 and 900.
var romanToInt = function(string) {
var reference = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
};
var result = 0;
for (var i = 0; i < string.length; i++) {
if (string[i] == 'I' && (string[i+1] == 'V' || string[i+1] == 'X')) {
result = result + (reference[string[i+1]] - reference[string[i]]);
i++;
} else if (string[i] == 'X' && (string[i+1] == 'L' || string[i+1] == 'C')) {
result = result + (reference[string[i+1]] - reference[string[i]]);
i++;
} else if (string[i] == 'C' && (string[i+1] == 'D' || string[i+1] == 'M')) {
result = result + (reference[string[i+1]] - reference[string[i]]);
i++;
} else {
result = result + reference[string[i]];
}
}
return result;
};
romanToInt('LVIII');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment