Leetcode——227. Basic Calculator II

题目原址

https://leetcode.com/problems/basic-calculator-ii/description/

题目描述

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.

Example 1:

Input: “3+2*2”
Output: 7

Example 2:

Input: ” 3/2 ”
Output: 1

Example 3:

Input: ” 3+5 / 2 ”
Output: 5

Note:

  • You may assume that the given expression is always valid
  • Do not use the eval built-in library function.

解题思路

给定一个字符串,字符串包含数字和+、-、*、/运算符,按照给定字符串求字符串的结果

使用栈来存储中间的运算结果,对于+和-的操作直接放如栈中,对于*和/的操作先从栈中取出一个数计算然后再放入栈中。sign记录的是上一次的运算符,sign初始值为+,因为首先栈中应该有值才能进行操作,所以第一个数一定要压入栈中。

AC代码

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();

        if(s.length() == 0) return s.charAt(0) - '0';
        int num = 0;
        char sign = '+';
        for(int i = 0; i < s.length(); i++) {
            if(Character.isDigit(s.charAt(i))) {
                num = num * 10 + s.charAt(i) - '0';
            }
            if((!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ') || i == s.length() - 1) {
                //操作数为+的直接压栈,为-的则将其负数压栈
                if(sign == '+') {
                    stack.push(num);
                }else if(sign == '-') {
                    stack.push(-num);
                }
                //如果是*和/的操作就先从栈中取出一个数进行计算,再将其放入栈中
                if(sign == '*') {
                    stack.push(stack.pop() * num);
                }else if(sign == '/') {
                    stack.push(stack.pop() / num);
                }
                //更改运算符,并将num值置0
                sign = s.charAt(i);
                num = 0;
            }
        }
        int ret = 0;
        for(int i: stack) {
            ret += i;
        }
        return ret;        
    }
}

感谢

https://blog.csdn.net/mine_song/article/details/70992441

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值