zoukankan      html  css  js  c++  java
  • c# 堆栈四则运算

    public static Double GetResultFromStr(string source)
           {
               string str = InsertBlank(source);
               string rpnExperssion = ConvertToRPN(str);
               return GetResult(rpnExperssion);
    
           }
      
            private static double GetValue(double left, double right, char _operator)  
            {  
                switch (_operator)  
                {  
                    case '+':  
                        return left+right;  
                    case '-':  
                        return left-right;  
                   case '*':  
                        return left*right;  
                    case '/':  
                        return left/right;  
                }  
                return 0;  
            }
    
            private static double GetResult(string source)  
            {
                try
                {
                    source = source.Trim();
                    Stack<string> stack = new Stack<string>();
                    var list = source.Split(' ');
                    for (int i = 0; i < list.Length; i++)
                    {
                        string current = list[i];
                        //bool  b = Regex.IsMatch(strNum, "^[0-9]*{1}quot;);  
                        if (GetNum(current))
                        {
                            stack.Push(current);
                        }
                        else if (OperatorLevel.ContainsKey(current))
                        {
                            double right = double.Parse(stack.Pop());
                            double left = double.Parse(stack.Pop());
                            stack.Push(GetValue(left, right, current[0]).ToString());
                        }
                    }
                    string aaa = stack.Pop().ToString();
                    return double.Parse(aaa);
                }
                catch (Exception e)
                { }
                return 0;
            }
    
            private static string ConvertToRPN(string source)  
            {
                try
                {
                    StringBuilder result = new StringBuilder();
                    Stack<string> stack = new Stack<string>();
                    string[] list = source.Split(' ');
                    for (int i = 0; i < list.Length; i++)
                    {
                        string current = list[i];
                        //if (Regex.IsMatch(current, "^([0-9]{1,}){1}quot;"))
                        if (GetNum(current))
                        {
                            result.Append(current + " ");
                        }
                        else if (OperatorLevel.ContainsKey(current))
                        {
                            if (stack.Count > 0)
                            {
                                var prev = stack.Peek();
                                if (prev == "(")
                                {
                                    stack.Push(current);
                                    continue;
                                }
                                if (current == "(")
                                {
                                    stack.Push(current);
                                    continue;
                                }
                                if (current == ")")
                                {
                                    while (stack.Count > 0 && stack.Peek() != "(")
                                    {
                                        result.Append(stack.Pop() + " ");
                                    }
                                    //Pop the "("  
                                    stack.Pop();
                                    continue;
                                }
                                if (OperatorLevel[current] < OperatorLevel[prev])
                                {
                                    while (stack.Count > 0)
                                    {
                                        var top = stack.Pop();
                                        if (top != "(" &&
                                            top != ")")
                                        {
                                            result.Append(top + " ");
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    stack.Push(current);
                                }
                                else
                                {
                                    stack.Push(current);
                                }
                            }
                            else
                            {
                                stack.Push(current);
                            }
                        }
                    }
                    if (stack.Count > 0)
                    {
                        while (stack.Count > 0)
                        {
                            var top = stack.Pop();
                            if (top != "(" && top != ")")
                            {
                                result.Append(top + " ");
                            }
                        }
                    }
                    return result.ToString().Trim();
                }
                catch(Exception e)
                { }
                return "";
            }
    
            private static string InsertBlank(string source)  
           {  
                StringBuilder sb = new StringBuilder();  
                var list = source.ToCharArray();  
                foreach (var temp in list)  
                {  
                    if (OperatorLevel.ContainsKey(temp.ToString()))  
                    {  
                        sb.Append(" ");  
                        sb.Append(temp.ToString());  
                        sb.Append(" ");  
                   }  
                    else  
                    {  
                        sb.Append(temp);  
                    }  
                }  
                return sb.ToString();          }
    
            private static Dictionary<string, int> OperatorLevel  
           {  
               get  
                {  
                    if(_operatorLevel==null)  
                    {  
                        _operatorLevel = new Dictionary<string, int>();  
                        _operatorLevel.Add("+", 0);  
                        _operatorLevel.Add("-", 0);  
                        _operatorLevel.Add("(", 1);  
                        _operatorLevel.Add("*", 1);  
                        _operatorLevel.Add("/", 1);  
                        _operatorLevel.Add(")", 0);  
                    }  
                    return _operatorLevel;  
                }  
            }  
    
               /// <summary>  
           /// 验证是不是数字(包含整数和小数)  
           /// </summary>  
           /// <param name="str"></param>  
           /// <returns></returns>  
           private static bool GetNum(string str)  
           {
               bool b = false;
               try
               {
                   double.Parse(str);
                   b = true;
               }
               catch (Exception e)
               { 
    
               }
               return b;
          }  
    View Code
  • 相关阅读:
    linux 定时脚本任务的创建
    win10 Edge 无法上网代理服务器错误
    CentOS 7 系统root用户忘记密码的重置方法
    通过挂载系统光盘搭建本地yum仓库的方法
    Oauth服务端协议开发
    mongodb 用户权限控制
    javascript 数组方法拼接html标签
    存储管理与linux内存寻址(1)
    原型模式
    背包,队列,栈的java实现
  • 原文地址:https://www.cnblogs.com/chengjunwei/p/4332608.html
Copyright © 2011-2022 走看看