美文网首页
LeetCode 13. Roman to Integer(Ja

LeetCode 13. Roman to Integer(Ja

作者: chengruru | 来源:发表于2018-08-08 15:08 被阅读0次

    题目:给定一个罗马数字,将其转换为整数。 保证输入在1到3999之间。

    思路分析:
           相邻两个罗马数字,如果前一个罗马数字(current )大于后一个罗马数字(after ),那么直接加上前一个数(current);如果前一个数小于后一个数,那么就加上前一个罗马数字的相反数(-current )。

    编码实现也就分两种情况考虑:
          ①,如果当前数字大于之后的数字,则加上当前数字
          ②,其他情况则减去这个数字

    代码实现如下:

    public int romanToInt(String s) {
            s = s+"*";  //为了方便处理最后一个字符
            char[] chars = s.toCharArray();
            int result = 0;
            HashMap<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);
            map.put('*', Integer.MIN_VALUE);
            int current = 0;
            int after = 0;
            int tmp = 0;
            for (int i = 0; i < chars.length - 1; i++){
                current = map.get(chars[i]);
                after = map.get(chars[i+1]);
                if (current < after){
                    current = -current;
                }
                result += current;
            }
            return result;
        }
    

    提交结果:


    13.png

    相关文章

      网友评论

          本文标题:LeetCode 13. Roman to Integer(Ja

          本文链接:https://www.haomeiwen.com/subject/wfqxbftx.html