leetcode-13- Roman numerals to Integer

 

problem:

 

 

solution:

Package com.example.demo; 

Import the java.util.HashMap;
 Import a java.util.Map; 

public  class Test13 { 

    / ** 
     * number to integer Rome 
     * Roman characters behind the front than character large, according to the characteristics provided two pointers, a current representative of the current is the current number, 
     * that number before a pre representatives, when accumulated to determine the size of the current pre and, if pre <current, represents the number mistake, the 
     * Save pre twice to (minus 2 because, without the number should have been, added, and once the original subtraction, or plus) 
     * For example: IV 
     * incorrect result is: 1 + 5 = 6 ==> 1 We should not add, because I and V is behind a number, but also added a behind I is added twice I 
     * therefore need to lose two I 
     * correct result: 4 
     * 
     * @param S 
     * @return 
     * / 
    public  int romanToInt (String S) { 
        the 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 res = 0;
        char[] chars = s.toCharArray();
        int pre = 1000;
        for (char c : chars) {
            Integer current = map.get(c);
            res += current;
            if (current > pre) {
                res = res - pre * 2;
            }
            pre = current;
        }
        return res;
    }

    public static void main(String[] args) {
        Test13 t = new Test13();
        int i = t.romanToInt("MCMXCIV");
        System.out.println(i);
    }
}

 

Guess you like

Origin www.cnblogs.com/nxzblogs/p/11225933.html