C# - 10以内的加减乘除

 

 

    class Program
    {
        static void Main(string[] args)
        {
            var source = "5+2*2-3*4/2";
            var result = Cal(source);
            Console.WriteLine(result);
        }

        static int Cal(string str)
        {
            var numStack = new Stack<int>();//存储数字的栈
            var opStack = new Stack<char>();//存储操作符的栈
            int result;
            foreach (var c in str)
            {
                if (IsNumeric(c, out var i))
                {
                    numStack.Push(i);
                    continue;
                }

                while (opStack.Count > 0)
                {
                    var f = Check(c, opStack);
                    if (f)
                    {
                        break;
                    }
                    result = Cal(numStack, opStack);
                    numStack.Push(result);
                }
                opStack.Push(c);
            }
            result = Cal(numStack, opStack);
            numStack.Push(result);
            return result;
        }

        /// <summary>
        /// 判断是否是数字
        /// </summary>
        /// <param name="c"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        static bool IsNumeric(char c, out int i)
        {
            var pattern = @"^\d+$";
            var rgx = new Regex(pattern);
            var flag = rgx.IsMatch(c.ToString());
            i = 0;
            if (flag)
            {
                i = Convert.ToInt32(c.ToString());
            }
            return flag;
        }

        /// <summary>
        /// 判断当前操作符的优先级是否高于栈顶的操作符
        /// </summary>
        /// <param name="c"></param>
        /// <param name="opStack"></param>
        /// <returns></returns>
        static bool Check(char c, Stack<char> opStack)
        {
            char op = opStack.Peek();
            if (op == * || op == /)
            {
                return false;
            }

            if (c == * || c == /)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="numStack"></param>
        /// <param name="opStack"></param>
        /// <returns></returns>
        static int Cal(Stack<int> numStack, Stack<char> opStack)
        {
            var num1 = numStack.Pop();
            var num2 = numStack.Pop();
            char op = opStack.Pop();
            switch (op)
            {
                case +:
                    return num2 + num1;
                case -:
                    return num2 - num1;
                case *:
                    return num2 * num1;
                case /:
                    return num2 / num1;
                default:
                    throw new Exception("not valid op");
            }
        }
    }

 

C# - 10以内的加减乘除

上一篇:Windows搭建Redis集群-详细教程


下一篇:C#6.0