Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- public class RomanNumerals {
- public static void main(String[] args) throws IOException {
- testRomanNumerals();
- interactiveRomanNumerals();
- }
- private static void interactiveRomanNumerals() throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String input;
- String output;
- while ((input = br.readLine()) != null && input.length() > 0) {
- System.out.println(toRomanNumerals(input));
- }
- }
- private static String toRomanNumerals(String input) {
- String output;
- StringBuffer data = new StringBuffer(input).reverse();
- output = "";
- for (int i = 0; i < data.length(); i++) {
- output = getRomanNumeral(data.charAt(i), i) + output;
- }
- return output;
- }
- private static String getRomanNumeral(char value, int placeIdx) {
- String[][] romanChars = {
- {"I", "V", "X"},
- {"X", "L", "C"},
- {"C", "D", "M"},
- {"M", "?", "?"}
- };
- String one = romanChars[placeIdx][0];
- String five = romanChars[placeIdx][1];
- String ten = romanChars[placeIdx][2];
- switch (value - '0') {
- case 1:
- return one;
- case 2:
- return one + one;
- case 3:
- return one + one + one;
- case 4:
- return one + five;
- case 5:
- return five;
- case 6:
- return five + one;
- case 7:
- return five + one + one;
- case 8:
- return five + one + one + one;
- case 9:
- return one + ten;
- default:
- return "";
- }
- }
- private static void testRomanNumerals() {
- testEquals("I", toRomanNumerals("1"));
- testEquals("VI", toRomanNumerals("6"));
- testEquals("XXXI", toRomanNumerals("31"));
- testEquals("XXIV", toRomanNumerals("24"));
- testEquals("L", toRomanNumerals("50"));
- testEquals("CCCLXIX", toRomanNumerals("369"));
- testEquals("CD", toRomanNumerals("400"));
- testEquals("CDXLVIII", toRomanNumerals("448"));
- testEquals("MCMXCVIII", toRomanNumerals("1998"));
- testEquals("MMDCCLI", toRomanNumerals("2751"));
- System.out.println("All test cases passed.");
- }
- private static void testEquals(String left, String right) {
- if (!left.equals(right))
- throw new RuntimeException("Test failed. left != right (" + left + " != " + right + ")");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment