基于栈实现整数加法算法

package com.hongjindong.Stack;

public class calculate {

	private int MaxSize = 20;
	int[] AStack = new int[MaxSize];
	int top = -1;

	public void push(int Value) {//入栈

		if (top >= MaxSize) {
			System.out.println("The stack is full! ");

		} else {

			top++;
			AStack[top] = Value;

		}
	}

	public int pop() {//出栈
		int temp;

		if (top < 0) {
			System.out.println("The stack is empty!");
			return -1;
		}

		temp = AStack[top];
		top--;
		return temp;
	}

	public boolean IsOperator(int operator) {//判断是否是运算符

		if (operator == 43 || operator == 45 || operator == 42
				|| operator == 47)
			return true;
		else
			return false;

	}

	public int Priority(int operator) {//判断优先级
		if (operator == 43 || operator == 45)
			return 1;
		else if (operator == 42 || operator == 47)
			return 2;
		else
			return 0;
	}

	public int TwoResult(int operator, int operand1, int operand2) {//两个数的运算

		switch (operator) {
		case 43:
			return (operand2 + operand1);
		case 45:
			return (operand2 - operand1);
		case 42:
			return (operand2 * operand1);
		case 47:
			return (operand2 / operand1);//注意这里写表达式的顺序
		}
		return 0;
	}

	public static void main(String[] args) {

		calculate Operator = new calculate();
		calculate Operand = new calculate();
		String Expression = "8*9-2*4";
		int Position = 0;
		int Operator1;
		int Operand1 = 0;
		int Operand2 = 0;
		int Result = 0;

		while (true) {

			if (Operator.IsOperator((int) Expression.charAt(Position))) {//判断读入的是否是运算符

				if (Operator.top != -1) {//如果运算符栈还有符号,判断两者的优先级
					if (Operator.Priority((int) Expression.charAt(Position)) <= Operator
							.Priority(Operator.AStack[Operator.top])) {//栈类的运算符优先级大,先计算
						Operand1 = Operand.pop();
						Operand2 = Operand.pop();
						Operator1 = Operator.pop();

						Operand.push(Operand.TwoResult(Operator1, Operand1,
								Operand2));
					}
				}
				Operator.push((int) Expression.charAt(Position));//运算符进栈
			}

			else {
				Operand.push((int) Expression.charAt(Position) - 48);//整数进栈

			}

			Position++;
			if (Position >= Expression.length())
				break;
		}

		while (Operator.top != -1) {//出栈

			Operand1 = Operand.pop();
			Operand2 = Operand.pop();
			Operator1 = Operator.pop();

			Operand.push(Operand.TwoResult(Operator1, Operand1, Operand2));
		}
		Result = Operand.pop();
		System.out.println("The expression result is :" + Result);

	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值