13. Roman to Integer

Example 1:
Input: "III"
Output: 3

Example 2:
Input: "IV"
Output: 4

Example 3:
Input: "IX"
Output: 9

Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

    public int romanToInt(String s) {
        int[] nums = new int[s.length()];
        for (int i = 0; i < nums.length; i++) {
            char cur = s.charAt(i); //此方法返回位于字符串的指定索引处的字符。该字符串的索引从零开始。
            if (cur == 'M') nums[i] = 1000; //处理字符串加''
            else if(cur == 'D') nums[i] = 500;
            else if(cur == 'C') nums[i] = 100;
            else if(cur == 'L') nums[i] = 50;
            else if(cur == 'X') nums[i] = 10;
            else if(cur == 'V') nums[i] = 5;
            else if(cur == 'I') nums[i] = 1;
        }
        int sum = 0;
        for(int i = 0; i < nums.length - 1; i++) { // 此处只能到i nums[i]) { // 如果后面的比前面的大,那么就需要减去前面一位的那个值
                sum -= nums[i];
            } else {
                sum += nums[i];
            }
        }
        return sum + nums[nums.length - 1];//因为前面的程序没有计算到最后一位,所以返回的时候要加上
    }
}

你可能感兴趣的:(13. Roman to Integer)