Skip to content

Instantly share code, notes, and snippets.

@mauricioaniche
Created April 22, 2019 09:11
Show Gist options
  • Save mauricioaniche/8708cec0721ee292553a391a16ab4673 to your computer and use it in GitHub Desktop.
Save mauricioaniche/8708cec0721ee292553a391a16ab4673 to your computer and use it in GitHub Desktop.
package tudelft.sqt;
import java.util.HashMap;
import java.util.Map;
public class RomanNumeral {
private static Map<Character, Integer> map;
static {
map = new HashMap<Character, Integer>() {{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
}
public int romanToInt(String s) {
int convertedNumber = 0;
for(int i = 0; i < s.length(); i++) {
int currentNumber = map.get(s.charAt(i));
int next = i+1 < s.length() ?
map.get(s.charAt(i+1)) : 0;
if(currentNumber > next)
convertedNumber += currentNumber;
else
convertedNumber -= currentNumber;
}
return convertedNumber;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment