leetcode 13 Roman to Integer

題目詳情

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

輸入一個字符串形式的羅馬數字,咱們須要將它轉換爲阿拉伯數字表示的整數。其中輸入的數字在1到3999的範圍內。code

想法

  • 這道題我不太熟悉的地方在於羅馬數字和阿拉伯數字之間的轉換規律。
  • 首先不一樣的字符表明不一樣的數,例如‘I’ = 1,'V' = 5,'X' = 10 等等。
  • 若是表明較小數的字符出如今較大數的左側,那麼應該減去這個左邊的數應該是被減去的。

解法

public int romanToInt(String s) {
        HashMap<Character,Integer> count = new HashMap<Character,Integer>();
        int res = 0;
        insertMap(count);
        for(int i=0;i<s.length()-1;i++){
            if(count.get(s.charAt(i)) < count.get(s.charAt(i+1))){
                res = res - count.get(s.charAt(i));
            }else{
                res = res + count.get(s.charAt(i));
            }
        }
        res = res + count.get(s.charAt(s.length()-1));

        return res;
    }
    public HashMap<Character,Integer> insertMap(HashMap<Character,Integer> count){
        count.put('I', 1);
        count.put('V', 5);
        count.put('X', 10);
        count.put('L', 50);
        count.put('C', 100);
        count.put('D', 500);
        count.put('M', 1000);
        return count;
    }
相關文章
相關標籤/搜索