task3
unknown
csharp
4 years ago
2.3 kB
8
Indexable
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; // you can also use other imports, for example: // using System.Collections.Generic; // you can write to stdout for debugging purposes, e.g. // Console.WriteLine("this is a debug message"); class Solution { static void checkNumberSize(int n) { if (n < 0 || n > (Math.Pow(2, 20) - 1)) { throw new Exception(); } } public int solution(string S) { try { Stack<int> stack = new Stack<int>(); string[] instructions = S.Split(' '); Console.WriteLine(); for (int i = 0; i < instructions.Length; i++) { switch (instructions[i]) { case "+": if (stack.Count < 2) { throw new Exception(); } else { int num = stack.Pop() + stack.Pop(); checkNumberSize(num); stack.Push(num); } break; case "-": if (stack.Count < 2) { throw new Exception(); }else { int second = stack.Pop(); int first = stack.Pop(); int num = second - first; checkNumberSize(num); stack.Push(num); } break; case "POP": stack.Pop(); break; case "DUP": stack.Push(stack.Peek()); break; default: int numToPush = Convert.ToInt32(instructions[i]); checkNumberSize(numToPush); stack.Push(numToPush); break; } } return stack.Peek(); } catch (Exception) { return -1; } } }
Editor is loading...