This is the 12th day of my participation in the August Challenge

13. Convert Roman numerals to whole numbers

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

Character value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, the Roman numeral 2 is written as II, which is the parallel 1. Write XII as X + II. Write XXVII as XX + V + II.

Usually, the smaller Roman numerals are to the right of the larger numerals. But there are exceptions, for example, 4 is not written as IIII, it’s written as IV. The number 1 is to the left of the number 5 and represents the number 4 when the larger number 5 decreases by 1. Similarly, the number 9 represents IX. This particular rule applies only to the following six situations:

I can be put to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be put to the left of D (500) and M (1000) to represent 400 and 900. Given a Roman numeral, convert it to an integer. Make sure the input is in the range of 1 to 3999.

Example 1:

Input: “III” Output: 3 Example 2:

Input: “IV” Output: 4

Their thinking

Make a map of the Roman numeral and the actual value it represents. Through this map, after obtaining a Roman numeral each time, we can directly obtain the decimal size of the Roman numeral, without the need for if condition judgment, and compare the size with the next Roman numeral

  • If the latter Roman numeral is large, it means this is 4,9,40,90… , so the current Roman numerals need to be subtracted

  • It’s the 5,6,7,8 case, in which case we can just add up, that’s what we want, just add the current Roman numerals

code

func romanToInt(s string) int {
	
	m,res,n := map[byte]int{'I': 1.'V': 5.'X': 10.'L': 50.'C': 100.'D': 500.'M': 1000},0.len(s)
	for i := 0; i <n ; i++ {
		cur := m[s[i]]
		if i<n- 1&&m[s[i+1]]>cur{
			res-=cur
		}else{
			res+=cur
		}
	}
	return res
}
Copy the code