Java solution using switch


  • 0
    D
    public int romanToInt(String s) {
        //I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)
        char[] data = s.toCharArray();
        int r = 0;
        for(int i = 0 ; i < data.length ; i++){
            int a = getIntByChar(data[i]);
            if(i < data.length - 1){
                int b = getIntByChar(data[i+1]);
                if(a < b) { // just like IV IX , if the data[i] < data[i+1] ,it means minus this data[i];
                    r -= a;
                }else{
                    r += a;
                }
            }else{
                r += a;
            }
        }
        return r;    
    }
    
    private int getIntByChar(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;
        }
        return 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.