Created
March 8, 2018 23:33
-
-
Save SubOptimal/863666cf80ae7822b6a26ef17e3c0465 to your computer and use it in GitHub Desktop.
roman numerals converter
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
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