224. 基本计算器
2021/12/20 23:49:51
本文主要是介绍224. 基本计算器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner; import java.util.Stack; class Solution { private void pushStack(Stack<Integer> stack, char sign, int num) { if (sign == '+') { stack.push(num); } else if (sign == '-') { stack.push(-num); } else if (sign == '*') { stack.push(stack.pop() * num); } else if (sign == '/') { stack.push(stack.pop() / num); } } private int[] solve(String str, int index) { Stack<Integer> stack = new Stack<>(); int num = 0; char sign = '+'; while (index < str.length() && str.charAt(index) != ')') { if (Character.isDigit(str.charAt(index))) { num = num * 10 + str.charAt(index++) - '0'; } else if (str.charAt(index) == '(') { int[] next = solve(str, index + 1); index = next[0] + 1; num = next[1]; } else if (str.charAt(index) == ' ') { index++; } else { pushStack(stack, sign, num); num = 0; sign = str.charAt(index++); } } pushStack(stack, sign, num); int sum = stack.stream().reduce(0, Integer::sum).intValue(); return new int[]{index, sum}; } public int calculate(String s) { if (s == null || s.length() == 0) { return 0; } return solve(s, 0)[1]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { System.out.println(new Solution().calculate(in.nextLine())); } } }
这篇关于224. 基本计算器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?
- 2024-05-30java excel上传--poi
- 2024-05-30安装笔记本应用商店的pycharm,再安排pandas等模块,说是没有打包工具?
- 2024-05-29java11新特性
- 2024-05-29哪些无用敏捷指标正在破坏敏捷转型?
- 2024-05-29鸿蒙原生应用再新丁!新华社 入局鸿蒙
- 2024-05-29设计模式 之 迭代器模式(Iterator)