Skip to content

Instantly share code, notes, and snippets.

@lbbedendo
Created June 23, 2020 11:37
Show Gist options
  • Save lbbedendo/6d5409da6f45afee448d8369f9de1787 to your computer and use it in GitHub Desktop.
Save lbbedendo/6d5409da6f45afee448d8369f9de1787 to your computer and use it in GitHub Desktop.
Roman to Integer
import java.util.Map;
public class RomanToInteger {
private static final Map<Character, Integer> symbols =
Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
public int convert(String romanNumeral) {
int result = 0;
for (int i = 0; i < romanNumeral.length(); i++) {
char currentChar = romanNumeral.charAt(i);
boolean isLastNumeral = i == romanNumeral.length() - 1;
if (isLastNumeral) {
return result + symbols.get(currentChar);
}
if (compare(currentChar, romanNumeral.charAt(i + 1)) < 0) {
int subtraction = convertSubtraction(currentChar, romanNumeral.charAt(i + 1));
result += subtraction;
i++;
} else {
result += symbols.get(currentChar);
}
}
return result;
}
private int compare(char a, char b) {
return Integer.compare(symbols.get(a), symbols.get(b));
}
private int convertSubtraction(char a, char b) {
return symbols.get(b) - symbols.get(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment