Roman To Integer

Given a string A representing a roman numeral.
Convert A into integer.

A is guaranteed to be within the range from 1 to 3999.

NOTE: Read more
details about roman numerals at Roman Numeric System



Input Format

The only argument given is string A.

Output Format

Return an integer which is the integer verison of roman numeral string.

For Example

Input 1:
    A = "XIV"
Output 1:
    14

Input 2:
    A = "XX"
Output 2:
    20
Method:

Add value to total, if next value is greater than current value, subtract current value instead

Solution:

Time: O(n)
Space: O(1)

public class Solution {
    public int romanToInt(String A) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        char[] arr = A.toCharArray();
        int total = 0;
        for (int i = 0; i < arr.length; i ++) {
            char c = arr[i];
            int val = map.get(c);
            if (i + 1 < arr.length && map.get(arr[i + 1]) > val) {
                total -= 2 * val;
            }
            total += val;
        }
        return total;
    }
}

class Solution {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        int sum = 0;
        int prev = 0;
        for (int i = 0; i < s.length(); i ++) {
            char c = s.charAt(i);
            int curr = map.get(c);
            if (curr > prev) {
                sum -= 2 * prev;
            }
            sum += curr;
            prev = curr;
        }
        return sum;
    }
}