roman To Decimal - Java java.lang

Java examples for java.lang:int Format

Description

roman To Decimal

Demo Code


//package com.java2s;

public class Main {
    public static int romanToDecimal(String roman) {
        int result = 0;
        while (roman.length() > 0) {
            if (startsWithSubtraction(roman)) {
                result += getCharValue(roman.charAt(1))
                        - getCharValue(roman.charAt(0));
                roman = roman.substring(2);
            } else {
                result += getCharValue(roman.charAt(0));
                roman = roman.substring(1);
            }/*from  ww  w. ja  va2s  . c  o m*/
        }
        return result;
    }

    private static boolean startsWithSubtraction(String roman) {
        return roman.length() > 1
                && getCharValue(roman.charAt(1)) > getCharValue(roman
                        .charAt(0));
    }

    private static int getCharValue(char c) {
        switch (c) {
        case 'M':
            return 1000;
        case 'D':
            return 500;
        case 'C':
            return 100;
        case 'L':
            return 50;
        case 'X':
            return 10;
        case 'V':
            return 5;
        case 'I':
            return 1;
        default:
            throw new IllegalArgumentException("" + c);
        }
    }
}

Related Tutorials