LeetCode 13. 罗马数字转整数

题目描述

🔥 13. 罗马数字转整数

思路分析

把一个小值放在大值的左边,就是做减法,否则为加法。

参考代码

1
write your code here

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int romanToInt(String s) {
        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;
        int pre = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            int cur = map.get(s.charAt(i));
            if (cur < pre) {
                res -= cur;
            } else {
                res += cur;
            }
            pre = cur;
        }
        return res;
    }
}

相似题目

题目 难度 题解
整数转罗马数字 Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/68898668
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!