Created
October 2, 2019 14:07
-
-
Save tommymcglynn/7abd330c7635940eecfd9446907c175e to your computer and use it in GitHub Desktop.
Solution to Devmates.co Roman Numerals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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