leetcode-13. Roman to Integer

leetcode12题的变式,罗马数字转换为阿拉伯数字

题目类型:

HashMap,字符串

题意:

Given a roman numeral, convert it to an integer.

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

我的思路:

66%

步骤:

  • 将字符串的各位转化为数字
  • 从前往后,如果当前罗马数字i大于后一位的罗马数字,直接转化
  • 如果小于后一位,则该位一定是需要减掉的部分 sum -= nums[i]
class Solution {
    public int romanToInt(String s) {
        int len = s.length();
        int[] num = new int[len];
        for(int i = 0;i < len; i++){
            switch (s.charAt(i)) {
            case 'M':
                num[i] = 1000;
                break;
            case 'D':
                num[i] = 500;
                break;
            case 'C':
                num[i] = 100;
                break;
            case 'L':
                num[i] = 50;
                break;
            case 'X':
                num[i] = 10;
                break;
            case 'V':
                num[i] = 5;
                break;
            case 'I':
                num[i] = 1;
                break;

            default:
                break;
            }
        }
        int res = 0;
        for(int i = 0; i < len - 1; i++){
            if (num[i] >= num[i + 1]) {
                res += num[i];
            }
            else {
                res -= num[i];
            }
        }
        res += num[len - 1];//最后一位一定为加
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/NNnora/article/details/81349871