[Toggle Comments]
package main // file: impl-002.go // The logic is the same as `impl-001.go`. // We just use a bigger lookup table. // // time: O(1); space: O(1) func romanToIntLookMore(s string) int { values := map[string]int{ "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900, } // Helpers singleSymbolValue := func(ix int) int { return values[string(s[ix])] } doubleSymbolValue := func(ix int) (int, bool) { v, b := values[s[ix:ix+2]] return v, b } total := 0 i := 0 lastIdx := len(s) - 1 for i <= lastIdx { // If we are at the end of the string, add the value of that // single symbol. if i == lastIdx { current := singleSymbolValue(i) total += current i++ continue } // If we have a matching double symbol, add its value and move the // index by two. current, found := doubleSymbolValue(i) if found { total += current i += 2 continue } // No matching double symbol, no problem. // Add the single symbol value instead. current = singleSymbolValue(i) total += current i += 1 } return total } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */