小白学习[leetcode]之13罗马数字转整数

题目的链接在这里:https://leetcode-cn.com/problems/roman-to-integer/


题目大意

在这里插入图片描述


一、示意图

在这里插入图片描述

二、解题思路

java实现

代码如下:

class Solution {
    
    
    public int romanToInt(String s) {
    
    
           //先用HashMap映射
        HashMap<Character,Integer> maps=new HashMap<>();
        //+‘0'的作用不是为了转换,而是让s多一个位置,这样才能让s的最后一个没有右边的值能进行输出
        s+='0';
        //再输入映射
        maps.put('I',1);
        maps.put('V',5);
        maps.put('X',10);
        maps.put('L',50);
        maps.put('C',100);
        maps.put('D',500);
        maps.put('M',1000);
        maps.put('0',0);

        int result=0;
        //再将String进行转化
        char[] chars=s.toCharArray();
        //再开始遍历,这里是没有到最后一个的,因为最后一个没有右边
        for(int i=0;i<chars.length-1;i++){
    
    
            //HashMap的get 和put 操作 get就是通过key键值来获得
            int cValue=maps.get(chars[i]);
            int nextValue= maps.get(chars[i+1]);
            //再就开始判断了,有两种可能性 如果左边的大于右边,那就加上,否则就减去(因为常规是左边大于右边的,如果不是的话
            //那就是按照逻辑 在原罗马数值上是用来加的
            //我不知道i+1这个判断需不需要,这里是排除了等于的
            if(cValue<nextValue){
    
    
                result-=cValue;
            }
            else{
    
    
                result+=cValue;
            }
        }
        return result;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41115379/article/details/114262306
今日推荐