Problem overview
The function romanToInt receives s, a valid Roman numeral of 1 to 15 letters, and returns its value, which is between 1 and 3,999. The seven letters are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000.
Usually the letters go from larger to smaller, and the value is their sum: XXXI is 10 + 10 + 10 + 1 = 31. Six pairs break that order, IV, IX, XL, XC, CD and CM, where a smaller letter stands just before a larger one and is subtracted. XIV is 10 + 4 = 14, and DCCCXLIX is 500 + 300 + 40 + 9 = 849.
Approach: subtract a letter that comes before a larger one
There is no need to find the six special pairs. Look at each letter together with the letter after it. If the next letter is worth more, the current one is the first half of a pair, so subtract its value. Otherwise add it. The last letter has no next letter and is always added.
For XIV this reads: X is followed by I, which is smaller, so add 10. I is followed by V, which is larger, so subtract 1. V is last, so add 5. The sum is 10 - 1 + 5 = 14. The subtraction of the small letter and the later addition of the large one together give exactly the pair's value, here 5 - 1 = 4.
One pass over the string with a lookup table of seven letters is enough, so the time is linear.
Step by step
- Build the table. Declare
valueswith a map literal and:=. Its type ismap[byte]int, because indexing a string,s[i], gives abyte, so the keys are byte literals such as'I'. - Start
totalat 0. It sums the letters' signed values. - Loop over the indexes with
for i := 0; i < len(s); i++. The index is needed to reach the next letter, so a plain loop over the letters would not do. - Look up the current letter:
value := values[s[i]]. ForXIVthat gives 10, then 1, then 5. - Subtract when a larger letter follows. The condition has two parts:
i + 1 < len(s)andvalues[s[i + 1]] > value. The key line istotal -= value. - Otherwise add it with an
elsebranch. The last letter always lands here. - Return
totalafter the loop.
The order of the two tests in step 5 matters. Go's && stops at the first part that is false, so when i + 1 < len(s) fails, s[i + 1] is never read. Reading it would panic with an index out of range.
The solution in Go
func romanToInt(s string) int {
values := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total := 0
for i := 0; i < len(s); i++ {
value := values[s[i]]
if i + 1 < len(s) && values[s[i + 1]] > value {
total -= value
} else {
total += value
}
}
return total
}
The Go details worth a closer look:
- Bytes and runes. A Go string is a sequence of bytes.
s[i]is abyte, which prints as a number: for"XIV",s[0]prints as88, the code of'X', whilestring(s[0])gives"X". Arangeloop over a string yieldsrunes instead. Using a rune as the key of thismap[byte]intdoes not compile:cannot use c (variable of type rune) as byte value in map index. For a numeral made of ASCII letters the byte loop is simplest. - Missing keys. Reading a key that is not in a map gives the zero value, so
values['Z']is0, not an error. The lesson guarantees valid input, so this never comes up, but it explains why bad input would quietly add nothing. - Map literal.
map[byte]int{'I': 1, ...}builds and fills the map in one expression. A map is created once per call, which is fine for seven entries. - Integer type.
totalis anint, which holds far more than 3,999, so there is no overflow concern.
Run on the examples, the function returns 31 for "XXXI", 14 for "XIV" and 849 for "DCCCXLIX". It also returns 1994 for "MCMXCIV", 3999 for "MMMCMXCIX" and 1 for "I".
Complexity
Each letter costs one or two map lookups and one addition or subtraction, so the time is O(n) for a string of length n. The map always holds seven entries, so the extra space is O(1).
Edge cases and common mistakes
- The last letter. It has no successor, so it must be added. Checking the bound first, as the condition does, handles this.
- A single letter.
"I"goes straight to theelsebranch and returns 1. - Several smaller letters before a larger one. A numeral like
XIVorMCMXCIVmixes additions and subtractions. Each letter is judged only against its right neighbour, and that is enough for valid numerals. - Equal neighbours. In
XXX, the next letter is equal, not larger, so the letter is added. Use a strict>. - Using
rangewith the byte map. It gives runes and does not compile, as shown above. Index the string withs[i]instead.
