13. Roman to Integer

罗马数字转整数,如图


image.png

需要注意的是IX,IV这样的
java环境

class Solution {
    public int romToInt(char s){
        switch(s){
            case 'I':
                return 1;
            case 'X':
                return 10;
            case 'V':
                return 5;
            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;
        for(int i=0;i<s.length();i++){
            if(i!=s.length()-1 && romToInt(s.charAt(i)) < romToInt(s.charAt(i+1))){
                res = res + romToInt(s.charAt(i+1)) - romToInt(s.charAt(i));
                i++;
            }
            else res += romToInt(s.charAt(i));
        }
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容