LC13. 罗马数字转整数

六月ゝ 毕业季﹏ 提交于 2020-01-12 19:38:27

1. 解法一

/**
 * @Classname Solution1
 * @Description TODO
 * @Date 2020/1/11 6:50
 * @Author SonnSei
 */
public class Solution1 {
    /* 优先匹配两个字符的 */
    public int romanToInt(String s) {
        int[] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] strs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            map.put(strs[i], value[i]);
        }
        int ret = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            char nextChar = '*';
            if (i < s.length() - 1) {
                nextChar = s.charAt(i + 1);
            }
            if (map.containsKey(""+c + nextChar )) {
                ret += map.get(""+c + nextChar );
                i++;
            } else {
                ret += map.get(c + "");
            }
        }
        return ret;
    }
}

2. 解法二

/**
 * @Classname Solution2
 * @Description TODO
 * @Date 2020/1/11 6:53
 * @Author SonnSei
 */
public class Solution2 {
    /**
     * 如果前一个数字比后一个数字小的话,代表发生的特殊情况
     * switch比hashmap还要快
     * @param s
     * @return
     */
    public int romanToInt(String s) {
        int ret = 0;
        int preValue = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int curVlue = getValue(c);
            ret +=curVlue;
            if (preValue < curVlue) {
                // IV=4,但是其实算的是I+V=6,所以需要减去两倍的pre
                ret-=preValue<<1;
            }
            preValue = curVlue;
        }
        return ret;
    }

    private int getValue(char ch) {
        switch(ch) {
            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;
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!