Drill

ProblemsC# › text

Evaluate a formula

hardtextStacksParsingRecursionC#

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

EvaluateExpression(text: string) → int

C# 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

public int EvaluateExpression(string text) {
    
}

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 C#
public int EvaluateExpression(string text) {
    string clean = text.Replace(" ", "").Replace("\t", "");
    int total = 0, term = 0, num = 0;
    char op = '+';
    for (int i = 0; i <= clean.Length; i++) {
        char c = i < clean.Length ? clean[i] : '#';
        if (c >= '0' && c <= '9') { num = num * 10 + (c - '0'); continue; }
        if (op == '+') { total += term; term = num; }
        else if (op == '-') { total += term; term = -num; }
        else if (op == '*') term = term * num;
        else { 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 C#