Simple Java solution


  • 0
    V

    public class Solution {

    public int romanToInt(String s) {
        HashMap<Character, Integer> values = new HashMap<Character, Integer>();
        values.put('I',1);
        values.put('V',5);
        values.put('X',10);
        values.put('L',50);
        values.put('C',100);
        values.put('D',500);
        values.put('M',1000);
        
        int ptr = s.length() - 1;
        int curr;
        int prev = 0;
        int result = 0;
        
        while(ptr >= 0) {
            curr = values.get(s.charAt(ptr));
            result = curr >= prev ? (result + curr) : (result - curr);
            prev = curr;
            ptr--;
        }
        
        return result;
    }
    

    }


Log in to reply
 

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