13. Roman to Integer

题目 13. Roman to Integer

image-567c637b

思路分析

代码实现

class Solution {

    int RtoI(char s){
        switch(s){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default : return 0;
        }
    }

    public int romanToInt(String s) {
        int res=0;
        int n = s.length();
        for(int i=0;i<n;i++){
            int curv = RtoI(s.charAt(i));
            if(i<n-1 && curv<RtoI(s.charAt(i+1))){
                res-=curv;
            }else{
                res+=curv;
            }
        }
        return res;
    }
}

同类题型

视频讲解