1. 程式人生 > >Leetcode 224: Basic Calculator

Leetcode 224: Basic Calculator

rar private else val expr int eval integer and

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.

 1 public class Solution {
 2     public int Calculate(string s) {
 3         var nums = new Stack<int>();
 4         var ops = new Stack<char>();
 5         
 6         var sc = s.ToCharArray();
 7         
 8         for (int
i = 0; i < sc.Length; i++) 9 { 10 if (sc[i] == ) 11 { 12 continue; 13 } 14 else if (sc[i] == ( || sc[i] == + || sc[i] == - ) 15 { 16 ops.Push(sc[i]); 17 } 18 else if
(sc[i] == )) 19 { 20 // the top should be ‘(‘ 21 ops.Pop(); 22 23 if (ops.Count > 0) 24 { 25 var op = ops.Pop(); 26 var n2 = nums.Pop(); 27 var n1 = nums.Pop(); 28 29 nums.Push(Calculate(n1, n2, op)); 30 } 31 } 32 else 33 { 34 int n1 = 0; 35 36 while (i < sc.Length && (int)sc[i] >= (int)0 && (int)sc[i] <= (int)9) 37 { 38 n1 = n1 * 10 + (int)sc[i] - (int)0; 39 i++; 40 } 41 42 i--; 43 44 if (ops.Count == 0 || ops.Peek() == () 45 { 46 nums.Push(n1); 47 } 48 else 49 { 50 nums.Push(Calculate(nums.Pop(), n1, ops.Pop())); 51 } 52 } 53 } 54 55 return nums.Pop(); 56 } 57 58 private int Calculate(int n1, int n2, char op) 59 { 60 return op == + ? n1 + n2 : n1 - n2; 61 } 62 }

Leetcode 224: Basic Calculator