Drill

ProblemsGo › text

Evaluate a formula

hardtextStacksParsingRecursionGo

A spreadsheet cell holds a small arithmetic formula, and the recalculation pass turns it into a number.

evaluateExpression(text: string) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func evaluateExpression(text string) int {
	
}

Worked examples

CallResult
evaluateExpression("2+3*4")14
evaluateExpression("10-2-3")5
evaluateExpression("7/2")3
evaluateExpression("2*3+4*5")26

Hint

Carry a running total plus one pending term. On + or - you bank the pending term; on * or / you fold the new number into it.

Reference solution in Go
func evaluateExpression(text string) int {
	clean := strings.Join(strings.Fields(text), "")
	total, term, num := 0, 0, 0
	op := byte('+')
	for i := 0; i <= len(clean); i++ {
		var c byte = '#'
		if i < len(clean) {
			c = clean[i]
		}
		if c >= '0' && c <= '9' {
			num = num*10 + int(c-'0')
			continue
		}
		switch op {
		case '+':
			total += term
			term = num
		case '-':
			total += term
			term = -num
		case '*':
			term = term * num
		default:
			if num == 0 {
				return 0
			}
			term = term / num
		}
		op = c
		num = 0
	}
	return total + term
}

The same problem in another language

More text problems in Go