My Accepted Simple Java Solution with switch case, so EASY !!!


  • 2
    H

    The idea is: if the value of current Roman character is bigger the previous one, the result should plus the value of the current character and minus the value of the previous one.. e.g. "CM" means 900, initialize variable result=0; the result should plus (1000 - 100)..

    public int romanToInt(String s) {

        // pre means previous Roman character, cur means current character
        int pre = 0, cur = 0, result = 0; 
        for(int i=0; i< s.length(); i++){
            switch(s.charAt(i)){
                case 'M': cur = 1000;
                    break;
                case 'D': cur = 500;
                    break;
                case 'C': cur = 100;
                    break;
                case 'L': cur = 50;
                    break;
                case 'X': cur = 10;
                    break;
                case 'V': cur = 5;
                    break;
                case 'I': cur = 1;
                    break;
            }
     
            if(cur > pre ){
                result = result - pre - prev + cur;
            }else
                result += cur ;
            pre = cur ;
        }
        return result;
    }

Log in to reply
 

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