Java Solution without Array or Map


  • 0
    L
    public class Solution {
        public int romanToInt(String s) {
            int sum = 0, m = 0, d = 0, c = 0, l = 0, x = 0, v = 0, i = 0;
    		for (int k = 0; k < s.length(); k++) {
    			switch(s.charAt(k)) {
    				case 'M' :
    					m++;
    					if(c != 0) c = c-2;
    					break;
    				case 'D' :
    					d++;
    					if(c != 0) c = c-2;
    					break;
    				case 'C' :
    					c++;
    					if(x != 0) x = x-2;
    					break;
    				case 'L' :
    					l++;
    					if(x != 0) x = x-2;
    					break;
    				case 'X' :
    					x++;
    					if(i != 0) i = i-2;
    					break;
    				case 'V' :
    					v++;
    					if(i != 0) i = i-2;
    					break;
    				case 'I' :
    					i++;
    					break;
    			}
    		}
    		sum = 1000*m + 500*d + 100*c + 50*l + 10*x + 5*v + i;
    		return sum;
        }
    }
    

Log in to reply
 

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