Java: Using Switch Case


  • 0
    I

    If a smaller value roman character comes left of higher value character, it acts as a negative of its own self.

        public int romanToInt(String s) {
            int len=s.length(),value=0;
            int I=1, V=5, X=10, L=50, C=100, D = 500, M=1000;
            
            for(int i=len-1;i>=0;i--){
                switch(s.charAt(i)){
                    case 'I':
                        value+= I;
                        break;
                    case 'V':
                        value+= V;
                        I=-1;
                        break;
                    case 'X':
                        value+= X;
                        I=-1;
                        break;
                    case 'L':
                        value+= L;
                        X=-10;
                        break;
                    case 'C':
                        value+= C;
                        X=-10;
                        break;
                    case 'D':
                        value += D;
                        C=-100;
                        break;
                    case 'M':
                        value += M;
                        C=-100;
                        
                }
            }
            return value;
        }
    }```

Log in to reply
 

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