Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 27, 2012 16:49
Show Gist options
  • Save zac-xin/4389754 to your computer and use it in GitHub Desktop.
Save zac-xin/4389754 to your computer and use it in GitHub Desktop.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
public class Solution {
char symbols[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
int values[] = {1000, 500, 100, 50, 10, 5, 1};
public int romanToInt(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if(s.length() == 0)
return 0;
s = s.toUpperCase();
for(int i = 0; i < symbols.length; i++){
int index = s.indexOf(symbols[i]);
if(index != -1){
return values[i] - romanToInt(s.substring(0, index)) + romanToInt(s.substring(index + 1));
}
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment