当前位置:网站首页>计算器(力扣)
计算器(力扣)
2022-06-28 14:27:00 【华为云】
title: 计算器
date: 2022-04-18 15:15:13
tags: 每天进步一点点系列
每日题目
题目:计算器
给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
示例:
示例 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; }}以上就是计算器的全部内容
版权声明:
原创博主:牛哄哄的柯南
个人博客链接:https://www.keafmd.top/
看完如果对你有帮助,感谢点击下面的==一键三连==支持!
[哈哈][抱拳]

加油!
共同努力!
Keafmd
都看到这里了,下面的内容你懂得,让我们共同进步!
边栏推荐
- Leetcode(88)——合并两个有序数组
- Adding virtual environments to the Jupiter notebook
- [binary tree] the minimum string starting from the leaf node
- 基于 Nebula Graph 构建百亿关系知识图谱实践
- G: maximum flow problem
- Votre Code parle? (1)
- Open source invites you to participate in openinfra days China 2022. Topic collection is in progress ~
- Deveco studio 3.0 editor configuration tips
- 从小小线虫谈起——溯源神经系统进化,开启生命模拟
- 猫狗队列
猜你喜欢

坐拥755万开发者的中国开源,进度几何?

接雨水系列问题

PC Museum - familiar and strange ignorant age

Four methods of thread termination

Tencent cloud international ECS has no network after logging in. How to troubleshoot?

Euler equation: a truly perfect formula in the history of mathematics!

Practice of constructing ten billion relationship knowledge map based on Nebula graph

线程的生命周期以及其中的方法

Can your code talk? (upper)

叮!Techo Day 腾讯技术开放日如约而至!
随机推荐
Ruijie switch configuration SSH password login command [easy to understand]
验证回文串
线程的生命周期以及其中的方法
Reverse a stack with recursive functions and stack operations only
基于asp.net的文献检索系统
智联招聘基于 Nebula Graph 的推荐实践分享
荐书丨《大脑通信员》:如果爱情只是化学反应,那还能相信爱情吗?
RAM ROM FLASH的区别
PC Museum - familiar and strange ignorant age
Can your code talk? (upper)
竞远安全冲刺创业板:拟募资4亿 启元投资与云游软件是股东
证券公司和银行哪个更安全 怎么办理开户最安全
开源社邀您参加OpenInfra Days China 2022,议题征集进行中~
Introduction to common components of IOT low code platform
Black apple installation tutorial OC boot "suggestions collection"
单一职责原则
Foreign trade SEO Webmaster Tools
只出现一次的数字(水了个简单题)
安杰思医学冲刺科创板:年营收3亿 拟募资7.7亿
2022 questions d'examen pour les cuisiniers chinois (Senior) et l'examen de simulation en ligne