Skip to content

Latest commit

 

History

History
28 lines (23 loc) · 397 Bytes

13.md

File metadata and controls

28 lines (23 loc) · 397 Bytes
func romanToInt(s string) int {
	constChar := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

	var i, num int
	for i < len(s) {
		var v1, v2 int
		v1 = constChar[s[i]]

		if i < len(s)-1 {
			v2 = constChar[s[i+1]]
		}

		if v1 >= v2 {
			num += v1
			i++
			continue
		}

		//handle special number
		t := v2 - v1
		num += t
		i += 2
	}

	return num
}