每日一题·5

题目:13. 罗马数字转整数

思路:

image-20230227141607224

代码:

class Solution {
    Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {{
        put('I', 1);
        put('V', 5);
        put('X', 10);
        put('L', 50);
        put('C', 100);
        put('D', 500);
        put('M', 1000);
    }};

    public int romanToInt(String s) {
        int ans = 0;
        int n = s.length();
        for (int i = 0; i < n; ++i) {
            int value = symbolValues.get(s.charAt(i));
            if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
                ans -= value;
            } else {
                ans += value;
            }
        }
        return ans;
    }
}

收获:

map的用法:

Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {{  //初始化
        put('I', 1);
        put('V', 5);
        put('X', 10);
        put('L', 50);
        put('C', 100);
        put('D', 500);
        put('M', 1000);
    }};
put('键','值');//输入键值
get('键') //获对应键的值
posted @ 2023-02-27 14:21  ZLey  阅读(10)  评论(0编辑  收藏  举报