C# solution: stack


  • 0
    B
    public class Solution 
    {
        public int Calculate(string s) 
    	{
    		var stack = new Stack<string>();
    
    		var numberStr = new StringBuilder();
            foreach(var c in s)
    		{
    			if (!char.IsWhiteSpace(c))
    			{
    				if (char.IsDigit(c))
    				{
    					numberStr.Append(c);
    				}
    				else
    				{
    					Calculate(stack, numberStr.ToString());
    
    					numberStr = new StringBuilder();
    					stack.Push($"{c}");
    				}
    			}
    		}
    
    		Calculate(stack, numberStr.ToString());
    
    		var result = 0;
    		while(stack.Any())
    		{
    			var curNumberStr = stack.Pop();
    
    			if (stack.Any())
    			{
    				var curSignStr = stack.Pop();
    
    				if (curSignStr == "-")
    				{
    					result += -int.Parse(curNumberStr);
    				}
    				else
    				{
    					result += int.Parse(curNumberStr);
    				}
    			}
    			else
    			{
    				result += int.Parse(curNumberStr);
    			}
    		}
    
    		return result;
        }
    
    	private void Calculate(Stack<string> stack, string secondNumberStr)
    	{
    		if (stack.Any() && (stack.Peek() == "*" || stack.Peek() == "/"))
    		{
    			var sign = stack.Pop();
    			var firstNumber = int.Parse(stack.Pop());
    			var secondNumber = int.Parse(secondNumberStr);
    
    			int result;
    			if (sign == "*")
    			{
    				result = firstNumber * secondNumber;
    			}
    			else //if (sign == "/")
    			{
    				result = firstNumber / secondNumber;
    			}
    
    			stack.Push($"{result}");
    		}
    		else
    		{
    			stack.Push(secondNumberStr);
    		}
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.