Golang Solution


  • 0
    J
    func romanToInt(s string) int {
    	ret := 0
    	for i, c := range s {
    		switch c {
    		case 'M':
    			ret += 1000
    			break
    		case 'D':
    			ret += 500
    			break
    		case 'C':
    			if i == len(s)-1 {
    				ret += 100
    				break
    			}
    			if s[i+1] == 'D' || s[i+1] == 'M' {
    				ret -= 100
    			} else {
    				ret += 100
    			}
    			break
    		case 'L':
    			ret += 50
    			break
    		case 'X':
    			if i == len(s)-1 {
    				ret += 10
    				break
    			}
    			if s[i+1] == 'L' || s[i+1] == 'C' {
    				ret -= 10
    			} else {
    				ret += 10
    			}
    			break
    		case 'V':
    			ret += 5
    			break
    		case 'I':
    			if i == len(s)-1 {
    				ret++
    				break
    			}
    			if s[i+1] == 'V' || s[i+1] == 'X' {
    				ret--
    			} else {
    				ret++
    			}
    			break
    		}
    	}
    	return ret
    }
    
    

Log in to reply
 

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