Yet another JAVA solution, clear exception handling

  • 0

    Hi everybody, in this solution putting individual symbol conversion into a separate method helps clear exception handling.

    class Solution {
        public int romanToInt(String s) throws NumberFormatException {
            int end = s.length()-1;
            //we start from adding the value of the last symbol to the result
            int res = arab(s.charAt(end));
            for(int i = end-1; i>=0; i--) {
                    // for the rest symbols we need to take into account the value of the next nearest symbol:
                    // if it is greater then the value of the current symbol,  
                    // the current symbol value is deducted from the total - 
                    // examples: 'I' in a 'IV' combination, 'X' in 'XC' combination
                    if(arab(s.charAt(i)) < arab(s.charAt(i+1))) res -= arab(s.charAt(i));
                    // otherwise the current symbol value adds up to total -
                    // examples: first 'I' in 'II' combination, 'V' in 'VI' combination.
                    else res += arab(s.charAt(i));
            return res;   
        private int arab (char roman) throws NumberFormatException {
            switch (roman) {
                case 'I': return 1;
                case 'V': return 5;
                case 'X': return 10;
                case 'L': return 50;
                case 'C': return 100;
                case 'D': return 500;
                case 'M': return 1000;
                default: throw new NumberFormatException();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.