Roman To Integer

题目

Given a roman numeral, convert it to an integer.

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

答案

class Solution {
    public int romanToInt(String s) {
        int s_len = s.length();
        int left = 0, right = s_len - 1, sum = 0;
        int[] map = new int[256];
        map['I'] = 1;
        map['V'] = 5;
        map['X'] = 10;
        map['L'] = 50;
        map['C'] = 100;
        map['D'] = 500;
        map['M'] = 1000;
        
        while(left <= right) {
            char c = s.charAt(left);
            if(left == right) {
                sum += map[c];
            }
            else {
                if(map[c] < map[s.charAt(left+1)]) sum -= map[c];
                else sum += map[c];
            }
            left++;
        }
        return sum;
    }
}

你可能感兴趣的:(Roman To Integer)