HJ50 四则运算
四则运算
描述:
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
数据范围:表达式计算结果和过程中满足 ∣val∣≤1000 ,字符串长度满足 1≤n≤1000
输入描述:输入一个算术表达式
输出描述:得到计算结果
eg:
输入:3+2*{1+2*[-4/(8-6)+7]}
输出:25
using System;
using System.Collections.Generic;public class Program
{public static void Main(){Dictionary<char, int> dic = new Dictionary<char, int>();dic.Add('(', 0);dic.Add(')', 0);dic.Add('[', 0);dic.Add(']', 0);dic.Add('{', 0);dic.Add('}', 0);dic.Add('+', 1);dic.Add('-', 1);dic.Add('*', 2);dic.Add('/', 2);Stack<int> num = new Stack<int>();Stack<char> sym = new Stack<char>();string str = Console.ReadLine();for (int i = 0; i < str.Length; i++){int res;//数字if (int.TryParse(str[i].ToString(),out res)){int left = i;int len = 1;while(i+1<str.Length && int.TryParse(str[i+1].ToString(), out res)){len++;i++;}int.TryParse(str.Substring(left, len), out res);num.Push(res);}else if (str[i]=='(' || str[i]=='{' || str[i]=='['){if (!int.TryParse(str[i+1].ToString(), out res)) num.Push(0);sym.Push(str[i]);}else if(str[i] == ')' || str[i] == '}' || str[i] == ']'){char symbol = sym.Peek();while (symbol != '(' && symbol != '{' && symbol != '['){calculate(ref num, ref sym);symbol = sym.Peek();}sym.Pop();}else{if (sym.Count > 0){char symbol = sym.Peek();while (sym.Count > 0 && dic[str[i]] <= dic[symbol]){calculate(ref num, ref sym);if (sym.Count > 0) symbol = sym.Peek();}}sym.Push(str[i]);}}while (sym.Count > 0){calculate(ref num, ref sym);}Console.WriteLine(num.Pop());}static void calculate(ref Stack<int> num, ref Stack<char> sym){int j = num.Pop();int i = num.Pop();char s = sym.Pop();int res = 0;if (s == '/') res= i / j;if (s == '*') res= i * j;if (s == '+') res= i + j;if (s == '-') res= i - j;num.Push(res);}
}