Golang roman to integer


  • 0
    L

    func romanToInt(s string) int {
    romanMap := map[string]int {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000,
    }
    sum := 0

    for index := 0; index < len(s); index++{
    	num := romanMap[string(s[index])]
    
    	// judge all s string is in romanMap
    	if num == 0  {
    		return sum
    	}
    
    	if string(s[index]) == "I" || string(s[index]) == "X" || string(s[index]) == "C" {
    		if len(s) > (index + 1) && num < romanMap[string(s[index + 1])]  {
    			num = romanMap[string(s[index + 1])]  - num
    			sum = sum + num
    			index = index + 1
    			continue
    		}
    	}
    
    	sum = sum + num
    
    }
    return sum
    

    }


Log in to reply
 

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