My Java solution using switch


  • 0
    H
    public int romanToInt(String s) {
        	int result = 0;
        	int[] signs = new int[6];
        	for (int i : signs) {
    			i = 1;
    		}
            for (int i = s.length() - 1; i >= 0; i--) {
                char curr = s.charAt(i);
                int power = 1;
                int sign = 0;
                switch (curr) {
                case 'I':	
                	power = 1;
                	sign = -1;
    				break;
                case 'V':
                	power = 5;
                	sign = 0;
    				break;
                case 'X':
                	power = 10;
                	sign = 1;
    				break;
                case 'L':
                	power = 50;
                	sign = 2;
    				break;
                case 'C':
                	power = 100;
                	sign = 3;
    				break;
                case 'D':
                	power = 500;
                	sign = 4;	
                	break;
                case 'M':
                	power = 1000;
                	sign = 5;
                	break;				
    			default:
    				break;
    			}
                result += signs[sign + 1] * power;
                if(sign != -1) 
                	if (signs[sign] != -1){
    		            for (int j = sign; j >= 0; j--) {
    		            	signs[j] = -1;
    					}
    	            }
    		}
            return result;
        }

Log in to reply
 

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