Created
March 27, 2017 19:41
-
-
Save olisikh/dcd7a5834293435da3a04b9bce29034a to your computer and use it in GitHub Desktop.
This file contains 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
public class RomanToInt { | |
private static final Map<String, Integer> conversionMap = new HashMap<String, Integer>() { | |
{ | |
put("I", 1); | |
put("IV", 4); | |
put("V", 5); | |
put("IX", 9); | |
put("X", 10); | |
put("XL", 40); | |
put("L", 50); | |
put("XC", 90); | |
put("C", 100); | |
put("CD", 400); | |
put("D", 500); | |
put("CM", 900); | |
put("M", 1000); | |
} | |
}; | |
public int romanToInt(String s) { | |
int acc = 0; | |
for (int i = 0; i < s.length(); i++) { | |
String n1 = String.valueOf(s.charAt(i)); | |
String n2 = i + 1 < s.length() ? String.valueOf(s.charAt(i + 1)) : "."; | |
if (!Objects.equals(n2, ".") && conversionMap.get(n1) < conversionMap.get(n2)) { | |
acc += conversionMap.get(n1 + n2); | |
i++; | |
} else { | |
acc += conversionMap.get(n1); | |
} | |
} | |
return acc; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment