Skip to content

Instantly share code, notes, and snippets.

@tommymcglynn
Created October 2, 2019 14:07
Show Gist options
  • Select an option

  • Save tommymcglynn/7abd330c7635940eecfd9446907c175e to your computer and use it in GitHub Desktop.

Select an option

Save tommymcglynn/7abd330c7635940eecfd9446907c175e to your computer and use it in GitHub Desktop.
Solution to Devmates.co Roman Numerals
private static final Map<Character, Integer> numeralMap = new HashMap<>();
static {
numeralMap.put('I', 1);
numeralMap.put('V', 5);
numeralMap.put('X', 10);
numeralMap.put('L', 50);
numeralMap.put('C', 100);
numeralMap.put('D', 500);
numeralMap.put('M', 1000);
}
public int solve(String input) {
int sum = 0;
char[] chars = input.toCharArray();
int top = 0;
for (int i = chars.length - 1; i >= 0; i--) {
int v = numeralMap.get(chars[i]);
if (v < top) {
sum -= v;
top = 0;
}
else {
sum += v;
top = v;
}
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment