[Toggle Comments]
package main // file: impl-003.go // The logic is the same as `impl-001.go`. // If we go from right to left instead, we can decide when to add and when // to subtract. The code will be cleaner too, since (unlike the previous // implementations) we will not need to move the pointer to index+2 anymore. // // time: O(1); space: O(1) func romanToIntReverse(s string) int { values := map[string]int{ "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } // Helper val := func(ix int) int { return values[string(s[ix])] } total := 0 lastIdx := len(s) - 1 total += val(lastIdx) // Trace the number from right to left. for i := lastIdx - 1; i >= 0; i-- { // If the current value is less than the one after it, subtract it. if val(i) < val(i+1) { total -= val(i) continue } // Otherwise, add the value. total += val(i) } return total } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */