# 13_ Roman numerals to Integer

Category Difficulty Likes Dislikes
algorithms Easy (61.07%) 841 -

my answer

public int romanToInt(String s) {
    int res = 0;
    for(int i= 0;i<s.length();i++){
        switch(s.charAt(i)){
            case 'I': {
                if(i+1<s.length() && (s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X')){
                    res-=1;
                    break;
                }
                res+=1;
            }
            break;
            case 'V': res+=5;
            break;
            case 'X':{
                if(i+1<s.length() && (s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C')){
                    res-=10;
                    break;
                }
                res+=10;
            }
            break;
            case 'L': res+=50;
            break;
            case 'C': {
                if(i+1<s.length() && (s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M')){
                    res-=100;
                    break;
                }
                res+=100;
            }
            break;
            case 'D': res+=500;
            break;
            case 'M': res+=1000;
            break;
            default:
            throw new IllegalArgumentException();
        }
    }
    return res;
}

Problem-solving ideas

  • Is not considered a special case, the judgment of each Roman numeral with swich
  • In exceptional cases plus if branch

The answer analysis

  • Long, may be packaged
  • Small left than the right when taking into account the special circumstances, to determine ways to change it
public int romanToInt(String s) {
    int res = 0;
    for(int i=0;i<s.length();i++){
        if(i+1<s.length() && (toInt(s.charAt(i))<toInt(s.charAt(i+1)))){
            res-=toInt(s.charAt(i));
            continue;
        }
        res+=toInt(s.charAt(i));
    }
    return res;
}
int toInt(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;
        default:
        throw new IllegalArgumentException();
    }
}

Reference program

public int romanToInt(String s) {
    int res = 0;
    HashMap<String,Integer> map = new HashMap<>();
    map.put("I", 1);
    map.put("V", 5);
    map.put("X", 10);
    map.put("L", 50);
    map.put("C", 100);
    map.put("D", 500);
    map.put("M", 1000);
    map.put("IV", 4);
    map.put("IX", 9);
    map.put("XL", 40);
    map.put("XC", 90);
    map.put("CD", 400);
    map.put("CM", 900);

    for(int i=0;i<s.length();i++){
        if(i+1<s.length() && (map.containsKey(s.substring(i, i+2)))){
            res+=map.get(s.substring(i, i+2));
            i++;
        }else{
            res+=map.get(s.substring(i, i+1));
        }
    }
    return res;

Not as I do

Remark

no



Guess you like

Origin www.cnblogs.com/mdz3201/p/leetcode_13.html