计算器/求表达式(算法)

给定一个包含正整数,加法(+),减法(-),乘法(*),除法(/)的算术表达式(括号除外),计算其结果,表达式仅包含非负整数,+,-,*,/四种运算符和空格。整数除法仅包含整数部分

示例1:

输入:“3+3*2”

输出 : 7

输入:“3/2”

输出:1

此算法利用栈来实现,一个栈用来存储数字,另一个栈用来存储表达式字符,逻辑1.数字直接入数字栈,2,运算符c >栈顶运算符 c直接入栈 3.运算符c <=栈顶运算符 栈顶出栈计算

代码:

package 算法.栈;

import java.util.Scanner;
import java.util.Stack;

public class 计算器 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        int result = calculate(str);
        System.out.println(result);
    }

    private static int calculate(String str) {
        Stack<Integer> nums = new Stack<>(); // 存放数字
        Stack<Character> ops = new Stack<>(); // 存放运算符
        int i = 0;
        int n = str.length();
        while (i < n) {
            char c = str.charAt(i);
            if (c == ' ') { // 跳过空格
                i++;
            } else if (isDigit(c)) { // 如果为数字
                int num = 0;
                while (i < n && isDigit(str.charAt(i))) {
                    num = num * 10 + str.charAt(i) - '0';
                    i++;
                }
                nums.push(num);
            } else { // 运算符
                if (ops.isEmpty() || prior(c, ops.peek())) { // 比较运算符等级
                    ops.push(c);
                } else {
                    while (!ops.isEmpty() && !prior(c, ops.peek())) {
                        fetchAndCal(nums, ops);
                    }
                    ops.push(c);
                }
                i++;
            }
        }
        while (!ops.isEmpty()) { // 最后检查计算栈内剩余的字符和数字
            fetchAndCal(nums, ops);
        }
        return nums.pop();
    }

    public static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    public static boolean prior(char a, char b) {
        if ((a == '*' || a == '/') && (b == '+' || b == '-')) {
            return true;
        } else {
            return false;
        }
    }

    public static void fetchAndCal(Stack<Integer> nums, Stack<Character> ops) {
        int num2 = nums.pop();
        int num1 = nums.pop();
        char op = ops.pop();
        int res = 0;
        switch (op) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num1 - num2;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num1 / num2;
                break;
        }
        nums.push(res);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值