1. 程式人生 > >LeetCode試題--將羅馬數字轉換成整數

LeetCode試題--將羅馬數字轉換成整數

題目描述如下: 

 

通過分析題目邏輯,羅馬數字使用Map儲存,呼叫String的CharAt方法提取字串中的特定位置字元。

map.get(Object key):獲取給定key對應的值;

char CharAt(int index):取字串中存放在index位置的字元;

程式碼實現如下:

    public static int romanToInt(String s){
        if(s==null || s.length()==0)
            return 0;
        Map<Character,Integer> m = new HashMap<Character,Integer>();
        m.put('I',1);
        m.put('V',5);
        m.put('X',10);
        m.put('L',50);
        m.put('C',100);
        m.put('D',500);
        m.put('M',1000);
        int len=s.length();
        int res = m.get(s.charAt(len-1));
        for(int i=len-1;i>=1;i--){
            //VI
            if(m.get(s.charAt(i)) <= m.get(s.charAt(i-1))){
                res += m.get(s.charAt(i-1));
            }
            //IV
            else{
                res -= m.get(s.charAt(i-1));
            }
        }
        return res;
    }