Solution to Problem 13 Roman to Integer


  • 0
    S

    Since we have the Roman representation, we can get each letter in the Roman representation. The only problem is to know that for each letter, whether it represents addition or subtraction.
    The only possible combinations where subtraction occurs are listed as follows:
    "I" on the left of "V" or "X" (1 on the left of 5 or 10) represents subtraction.
    "X" on the left of "L" or "C" (10 on the left of 50 or 100) represents subtraction.
    "C" on the left of "D" or "M" (100 on the left of 500 or 1000) represents subtraction.
    The letters mentioned above ("I", "X" and "C" respectively) represent subtraction, and the other letters represent addition. Therefore, the integer value of the Roman can be calculated.

    public class Solution {
    	public int romanToInt(String s) {
    		ArrayList<String> romans = new ArrayList<String>();
    		char[] romanChar = s.toCharArray();
    		int length = romanChar.length;
    		String str = "";
    		for (int i = 0; i < length; i++) {
    			if (str.length() == 0 || romanChar[i] == str.charAt(0))
    				str += romanChar[i];
    			else {
    				romans.add(str);
    				str = "";
    				str += romanChar[i];
    			}
    		}
    		if (str.length() > 0)
    			romans.add(str);
    		int size = romans.size();
    		char[] romanLetters = new char[size];
    		int[] romanInt = new int[size];
    		for (int i = 0; i < size; i++) {
    			String currentStr = romans.get(i);
    			char currentChar = currentStr.charAt(0);
    			romanLetters[i] = currentChar;
    			int counts = currentStr.length();
    			romanInt[i] = romanToInt(currentChar) * counts;
    		}
    		for (int i = 0; i < size - 1; i++) {
    			if (romanLetters[i] == 'I' && (romanLetters[i + 1] == 'V' || romanLetters[i + 1] == 'X'))
    				romanInt[i] *= -1;
    			if (romanLetters[i] == 'X' && (romanLetters[i + 1] == 'L' || romanLetters[i + 1] == 'C'))
    				romanInt[i] *= -1;
    			if (romanLetters[i] == 'C' && (romanLetters[i + 1] == 'D' || romanLetters[i + 1] == 'M'))
    				romanInt[i] *= -1;
    		}
    		int integer = 0;
    		for (int i = 0; i < size; i++)
    			integer += romanInt[i];
    		return integer;
    	}
    
    	public int romanToInt(char c) {
    		switch (c) {
    		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:
    			return 0;
    		}
    	}
    }
    

Log in to reply
 

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