Roman to Integer

来源:互联网 发布:网络用语犼是什么意思 编辑:程序博客网 时间:2024/06/05 16:52
public class Solution {
    public int romanToInt(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int n = s.length();
        int pre = 1001;
        int ret = 0;
        for(int i = 0; i< n; i++){
            int now = map(s.charAt(i));
            if(now<=pre){
                ret += now;
            }
            if(now>pre){
                ret += now;
                ret -= 2*pre;
            }
            pre = now;
        }
        return ret;
    }
    public int map(char c){
        switch(c){
            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;
            }
    return 0;
    }
    
}
原创粉丝点击