java solution


  • 0
    M
    public int romanToInt(String s) {
    	    int result = 0;
    	    int len = s.length();
    	    int last = 1000;
    	    for(int i = 0 ; i < len ; ++i) {
    	    	char ch = s.charAt(i);
    	    	int num = getIntByRoman(ch);
    	    	if(num > last) {
    	    		result = result - last + (num - last);
    	    	}else {
    	    		result += num;
    	    	}
    	    	last = num;
    	    }
    	    return result;
    }
    	 
    public int getIntByRoman(char ch) {
    	switch(ch) {
    		case 'M' : 
    		        return 1000;
    		 case 'D' :
    		 	return 500;
    		 case 'C' :
    		 	return 100;
    		 case 'L' :
    		 	return 50;
    		 case 'X' :
    		 	return 10;
    		 case 'V' :
    		 	return 5;
    		 case 'I' :
    		 	return 1;
    		 default :
    		 	return 0;
    	}
    }
    

Log in to reply
 

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