Simple solution Java 107 MS


  • 0
    C

    The logic is simple, reading for last index, we add the corresponding values of a Roman numeric if the previous value is higher or equal, else subtract.

    XL = 50-10 = 40 because X>L
    LX = 50 + 10 = 60 because X>L

    public class Solution {
        public int romanToInt(String s) {
            HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
            hashMap.put('I', 1);
            hashMap.put('V', 5);
            hashMap.put('X', 10);
            hashMap.put('L', 50);
            hashMap.put('C', 100);
            hashMap.put('D', 500);
            hashMap.put('M', 1000);
            
            int number =0 ;
            
        	for(int i = s.length() -1 ;i>=0;i-- ){
        		
        		if(i!= 0 && hashMap.get(s.charAt(i))>hashMap.get(s.charAt(i-1))){
        			number = number + hashMap.get(s.charAt(i)) - hashMap.get(s.charAt(i-1));
        			i--;
        		}else{
        			number +=hashMap.get(s.charAt(i));
        		}
        		
        	}
        	return number;
        }
    }
    

Log in to reply
 

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