Easy JavaScript solution with details


  • 0
    // APPROACH  
    // split string into an array
    // start with a result of 0
    // iterate over the numbers 
    	// if there is a number larger than the current smallest number 
    		// subtract 2* the current smallest number*the number of times the smallest number has appeared from the result
        // reset the current smallest number if there is a smaller number
    	// add to result
    
    var romanToInt = function(s) {
      var romanArray = s.split('');
      var result = 0;
    
      var currentSmallest = {
      	value: undefined,
      	run: 0
      };
        
      var romanIntsMap = {
    	I: 1,
    	V: 5,
    	X: 10,
    	L: 50,
    	C: 100,
    	D: 500,
    	M: 1000
      };  
    
      for(var i = 0; i < romanArray.length; i++){
      	var currentRoman = romanArray[i];
      	if(romanIntsMap[currentRoman] > currentSmallest.value){
      		result -= 2* currentSmallest.value * currentSmallest.run
      	} 
      	if(currentSmallest.value === undefined || currentSmallest.value > romanIntsMap[currentRoman]){
      		currentSmallest.value = romanIntsMap[currentRoman];
      		currentSmallest.run = 1;
      	}
    
    	result += romanIntsMap[currentRoman];
      }
      return parseInt(result);  
    };

Log in to reply
 

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