Golang Simple, no Recursion, going backwards, with comments


  • 0
    A
    func romanToInt(s string) int {
    	roman := map[byte]int{
    		'I': 1,
    		'V': 5,
    		'X': 10,
    		'L': 50,
    		'C': 100,
    		'D': 500,
    		'M': 1000,
    	}
    
    	var sum int
    	maxRank := 1                       // Largest 'numeral' seen so far
    	for i := len(s) - 1; i >= 0; i-- { //Backwards
    		cur := roman[s[i]]
    		if cur < maxRank { // If we have seen bigger (e.g. on the I in IV), subtract
    			sum -= cur
    		} else { // If we haven't seen bigger (e.g. on the I in VI), add
    			sum += cur
    			maxRank = cur // Keep track of the biggest rank seen
    		}
    	}
    	return sum
    }
    

Log in to reply
 

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