Skip to content

Instantly share code, notes, and snippets.

@SubOptimal
Created March 8, 2018 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SubOptimal/863666cf80ae7822b6a26ef17e3c0465 to your computer and use it in GitHub Desktop.
Save SubOptimal/863666cf80ae7822b6a26ef17e3c0465 to your computer and use it in GitHub Desktop.
roman numerals converter
import java.util.HashMap;
import java.util.Map;
public class RomanNumber {
static final Map<Character, Integer> ROMAN_NUMERALS;
static {
HashMap<Character, Integer> m = new HashMap<>();
m.put('I', 1);
m.put('V', 5);
m.put('X', 10);
m.put('L', 50);
m.put('C', 100);
m.put('D', 500);
m.put('M', 1000);
ROMAN_NUMERALS = m;
}
static int romanToDecimal(String roman) {
int[] left = new int[1];
return new StringBuilder(roman).reverse().chars()
.map(i -> ROMAN_NUMERALS.get((char) i))
.map((right) -> {
int result = right < left[0] ? -right : right;
left[0] = right;
return result;
}).sum();
}
public static void main(String[] args) {
String roman = "XLII";
int decimal = romanToDecimal(roman);
System.out.printf("roman: %s decimal: %d%n", roman, decimal);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment