Try   HackMD

Leetcode 13. Roman to Integer (C語言)

  • 題目
    Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
    ​​Symbol       Value
    ​​I             1
    ​​V             5
    ​​X             10
    ​​L             50
    ​​C             100
    ​​D             500
    ​​M             1000
    
    For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
  • 範例
Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
int cal1(char c){
    switch(c){
        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;
    }    
    return 0;
}

int romanToInt(char * s){
    int i,length=strlen(s),temp=0,val=0;
    for(i=0;i<length;i++){
        if(i==length-1){
            val+=cal1(s[i]);
            break;
        }
        if((temp=cal1(s[i+1])-cal1(s[i]))>0){
            val+=temp;
            i++;
            temp=0;
            continue;
        }        
        val+=cal1(s[i]);
    }
    return val;
}

思路:羅馬數字正常由大到小排列(M>D>C>L>X>V>I),一但有小到大的情況發生(e.g. IV,IX),這時候就把後者減前者(IV=5-1=4)。