Solution to Roman Number to Integer


  • 0
    F
    public int romanToInt(String s) {
            HashMap<Character, Integer> hashMap = new HashMap<>();
            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 value = 0;
    
            for (int i = 0; i < s.length(); i++) {
                if (i >= (s.length() - 1)) {
                    if (i == s.length() - 1) {
                        value += hashMap.get(s.charAt(i));
                        return value;
                    } else {
                        return value;
                    }
                }
                if (hashMap.get(s.charAt(i)) < hashMap.get(s.charAt(i + 1))) {
                    value += hashMap.get(s.charAt(i+1)) - hashMap.get(s.charAt(i));
                    i++;
                } else {
                    value += hashMap.get(s.charAt(i));
                }
            }
    
            return value;
        }

Log in to reply
 

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