计算器(力扣)

简介: 计算器(力扣)

每日题目

题目:计算器


给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。


表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。


示例:


示例 1:


输入: “3+2*2”

输出: 7


示例 2:


输入: " 3/2 "

输出: 1


示例 3:


输入: " 3+5 / 2 "

输出: 5


说明:


你可以假设所给定的表达式都是有效的。

请不要使用内置的库函数 eval。


小坑,字符串里有空格,需要替换掉


代码:

class Solution {
    public int calculate(String s) {
        s =s.replaceAll(" ","");
        Deque<Integer> stack = new ArrayDeque<>();
        //先把第一个加进去
        char flag = '+';
        //数字的初始值
        int num = 0;
        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)) || i==s.length()-1){
                if(flag=='+'){
                    stack.push(num);
                }else if(flag=='-'){
                    stack.push(-num);
                }else if(flag=='*'){
                    stack.push(stack.pop()*num);
                }else if(flag=='/'){
                    stack.push(stack.pop()/num);
                }
                flag = s.charAt(i);
                num =0;
            }
        }
        //遍历栈,累加结果
        int res =0;
        while(!stack.isEmpty()){
            res += stack.pop();
        }
        return res;
    }
}

以上就是计算器的全部内容


相关文章
|
4月前
leetcode-224:基本计算器
leetcode-224:基本计算器
17 0
|
4月前
|
存储 算法
算法题解-基本计算器2
算法题解-基本计算器2
|
9月前
|
JavaScript
BugKu CTF 计算器 解题思路
BugKu CTF 计算器 解题思路
56 0
|
11月前
|
存储
LeetCode刷题集(五)(LeetCode1.两数之和)
LeetCode刷题集(五)(LeetCode1.两数之和)
61 0
|
算法 C语言
想说说关于在刷题网站(牛客 、C语言网、力扣)上测试样例过了但是OJ判错这档子事
想说说关于在刷题网站(牛客 、C语言网、力扣)上测试样例过了但是OJ判错这档子事
|
测试技术 C++
牛客网输入输出练习c++ 个人版题解
牛客网输入输出练习c++ 个人版题解
264 0
牛客网输入输出练习c++ 个人版题解
|
Python
LeetCode 1. 两数之和【新方式】
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
84 0
|
前端开发 Python
Leecode加法题目3个 每日练习 Python实现
Leecode加法题目3个 每日练习 Python实现
87 0
Leecode加法题目3个 每日练习 Python实现
自制计算器,实现加减乘除
自制计算器,实现加减乘除
84 0