224.227. Basic Calculator I II

本文介绍了一种使用两个栈实现的基本计算器,能够解析包含加减乘除及括号的数学表达式,并提供具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

224. Basic Calculator

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.

表达式计算,基本思路是维护两个栈,一个操作数栈,一个数字栈,扫描字串,遇到空格字符忽略,遇到数字字符入栈(注意数字字符比如288有三位,字符也要相应取三位才能正确取出数字),遇到操作数,如果是左括号,入栈,如果是其他的操作符,栈非空的情况下看栈顶元素和当前操作符的关系,如果栈顶的操作符优先级大于等于当前操作符,就在数字栈里面弹出两个数,做相应的操作以后入栈直到变成以下情况为止:栈空、栈顶是左括号、栈顶元素优先级小于当前操作数。 然后把当前操作数入栈。遇到右括号也是弹出操作数和两个数字做相应的操作直到弹出的字符是左括号即完成匹配为止。

public static int calculate(String s)
	{
		int len=s.length();
		if(len<1)
			return 0;
		
		Stack<Integer> numstack=new Stack<>();
		Stack<Character> opstack=new Stack<>();
		
		int i=0;
		for(;i<len;)
		{
			char c=s.charAt(i);
			if(c=='(')
				opstack.push(c);
			else if(c=='+'||c=='-')
			{
				while(!opstack.isEmpty()&&(opstack.peek()=='+'||opstack.peek()=='-'))
				{
					char topchar=opstack.pop();
					int a=numstack.pop();
					int b=numstack.pop();
					if(topchar=='+')
						numstack.push(a+b);
					else if(topchar=='-')
						numstack.push(b-a); 
				}
				opstack.push(c);
			}
			else if(c>='0'&&c<='9')
			{
				int j=i;
				StringBuilder sb=new StringBuilder();
				while(j<len&&s.charAt(j)>='0'&&s.charAt(j)<='9')
					{
						sb.append(s.charAt(j));
						j++;
					}
				numstack.push(Integer.parseInt(sb.toString()));
				i=j-1;
			}
			else if(c==')')
			{
				while(true)
				{
					char topchar=opstack.pop();
					if(topchar=='(')
						break;
					int a=numstack.pop();
					int b=numstack.pop();
					if(topchar=='+')
						numstack.push(a+b);
					else if(topchar=='-')
						numstack.push(b-a);
				}
			}
			i++;	
		}
		while(!opstack.isEmpty())
		{
			char topchar=opstack.pop();
			int a=numstack.pop();
			int b=numstack.pop();
			if(topchar=='+')
				numstack.push(a+b);
			else if(topchar=='-')
				numstack.push(b-a);
		}
		
		return numstack.pop();
		
	}



227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

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


public static int calculate(String s)
	{
		int len=s.length();
		if(len<1)
			return 0;
		
		Stack<Integer> numstack=new Stack<>();
		Stack<Character> opstack=new Stack<>();
		int[] priority=new int[128];
		priority['+']=10;
		priority['-']=10;
		priority['*']=20;
		priority['/']=20;
		priority['(']=5;
		
		int i=0;
		for(;i<len;)
		{
			char c=s.charAt(i);
			if(c=='(')
				opstack.push(c);
			else if(priority[c]==10||priority[c]==20)
			{
				while(!opstack.isEmpty()&&(priority[opstack.peek()]>=priority[c]))
				{
					char topchar=opstack.pop();
					int a=numstack.pop();
					int b=numstack.pop();
					numstack.push(dooperator(a, b, topchar));
				}
				opstack.push(c);
			}
			else if(c>='0'&&c<='9')
			{
				int j=i;
				StringBuilder sb=new StringBuilder();
				while(j<len&&s.charAt(j)>='0'&&s.charAt(j)<='9')
					{
						sb.append(s.charAt(j));
						j++;
					}
				numstack.push(Integer.parseInt(sb.toString()));
				i=j-1;
			}
			else if(c==')')
			{
				while(true)
				{
					char topchar=opstack.pop();
					if(topchar=='(')
						break;
					int a=numstack.pop();
					int b=numstack.pop();
					numstack.push(dooperator(a, b, topchar));
				}
			}
			i++;	
		}
		while(!opstack.isEmpty())
		{
			char topchar=opstack.pop();
			int a=numstack.pop();
			int b=numstack.pop();
			numstack.push(dooperator(a, b, topchar));
		}
		
		return numstack.pop();
		
	}
	
	public static int dooperator(int a,int b,char op)
	{
		int result=0;
		switch (op)
		{
			case '+':
				result=b+a;
				break;
			case '-':
				result=b-a;
				break;
			case '*':
				result=b*a;
				break;
			case '/':
				result=b/a;
				break;
				
			default:
				break;
		}
		return result;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值