My 7~8ms solution with too many hard codes


  • -1
    S
    public static int romanToInt(String s) {
    		int sum = 0;
    		int sumTemp = 0;//I,X,C,的和
    		for(int i=0;i<s.length();i++){
    			switch(s.charAt(i)){
    			case 'I':
    				sumTemp += 1;
    				break;
    			case 'V':
    				sum += 5;
    				if(sumTemp%10 == 1){
    					sum = sumTemp - 2 + sum;
    					sumTemp = 0;
    				}
    				break;
    			case 'X':
    				sumTemp += 10;
    				if(sumTemp%10 == 1){
    					sum = sumTemp - 2 + sum;
    					sumTemp = 0;
    				}
    				break;
    			case 'L':
    				sum += 50;
    				if(sumTemp%100 == 10){
    					sum = sumTemp - 20 + sum;
    					sumTemp = 0;
    				}
    				break;
    			case 'C':
    				sumTemp += 100;
    				if(sumTemp%100 == 10){
    					sum = sumTemp - 20 + sum;
    					sumTemp = 0;
    				}
    				break;
    			case 'D':
    				sum += 500;
    				if(sumTemp == 100){
    					//说明之前出现过C
    					sum -= sumTemp;
    					sumTemp = 0;
    				}
    				break;
    			case 'M':
    				sum += 1000;
    				if(sumTemp == 100){
    					//说明之前出现过C
    					sum -= sumTemp;
    					sumTemp = 0;
    				}
    				break;
    			}
    		}
    		sum+=sumTemp;
    		return sum;
    	}

Log in to reply
 

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