Coding problem
Work out a postfix calculation
The task
A calculator app sends each calculation to the server as tokens in postfix order: every operator comes after its two numbers, so "2 3 4 * +" means 2 + 3 × 4 and needs no brackets.
Complete EvaluatePostfix(string[] tokens). Each token is an integer, which may be negative (such as "-7"), or one of "+", "-", "*" and "/". Apply each operator to the two values before it, the earlier value on the left. Division drops the remainder and truncates toward zero, as C#'s / does with ints. The calculation is always valid, never divides by zero, and every value along the way fits in an int.
Signature
public static int EvaluatePostfix(string[] tokens)
Examples
["2", "3", "4", "*", "+"]→14. 3 * 4 = 12 comes first, then 2 + 12.["8", "3", "-"]→5. The earlier value, 8, is on the left.
Limits: Up to 300,000 tokens.
The tests check: one number, a negative number alone, each operator, the order of the two values, division toward zero for negative values, a longer calculation, and 262,143 tokens in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// Evaluates integer tokens and + - * / given in postfix order.
public static int EvaluatePostfix(string[] tokens)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.