Java solution using only arrays


  • 0
    S

    New to coding, this is the easy way I can think of, and I don't know how to improve this solution.

    public int romanToInt(String s){
    	int num = 0;
    	int plus = 0;
    	int minus = 0;
    
    	String roman = "IVXLCDM";
    	int[] nums = {1,5,10,50,100,500,1000};
    
    	for (int i = 0; i < s.length() - 1; i++){
    		int index1 = roman.indexOf(s.charAt(i));
    		int index2 = roman.indexOf(s.charAt(i + 1));
    		if (index1 < index2) {
    			minus = minus + nums[index1];
    		} else {
    			plus = plus + nums[index1]; 
    		}
    	}
    	num = plus - minus + nums[roman.indexOf(s.charAt(s.length()-1))];
    	return num;
    }

Log in to reply
 

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