Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
public class Solution { public int calculate(String s) { char[] charArray = s.toCharArray(); Stack<Integer> stack = new Stack<>(); int res = 0; int sign = 1; stack.push(1); for (int i = 0; i < charArray.length; i++) { if (Character.isDigit(charArray[i])) { int num = charArray[i] - '0'; int j = i + 1; while (j < charArray.length && Character.isDigit(charArray[j])) { num = num * 10 + charArray[j] - '0'; j++; } res += sign * stack.peek() * num; i = j - 1; } else if (charArray[i] == '+') { sign = 1; } else if (charArray[i] == '-') { sign = -1; } else if (charArray[i] == '(') { stack.push(sign * stack.peek()); sign = 1; } else if (charArray[i] == ')') { stack.pop(); } else { ; } } return res; } }
public class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<>(); int res = 0; int sign = 1; int num = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch <= '9' && ch >= '0') { num = 10 * num + ch - '0'; } else if (ch == '+') { res += sign * num; sign = 1; num = 0; } else if (ch == '-') { res += sign * num; sign = -1; num = 0; } else if (ch == '(') { stack.push(res); stack.push(sign); res = 0; sign = 1; } else if (ch == ')') { res += sign * num; num = 0; res *= stack.pop(); res += stack.pop(); } } if (num != 0) { res += sign * num; } return res; } }
相关推荐
This is basic Calculator program written in C#.
This is a basic calculator written in Visual Basic.
Algorithm-BasicCalculator.zip,ios objective-c使用堆栈实现算术表达式求值和基本的四种算术操作(包括括号操作),算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
basicCalculator
自动翻译的文本:Basic Calculator 1.0使您可以从两位数的基数执行操作。 请注意不要将项目放在逗号中,否则会出现错误。 有关www.mexson.c.la的更多信息
basicCalculator 这是使用javascript开发的基本计算方法。
simple Visual Basic calculator
非常基本的Java计算器,使用Java Web Start! 您所要做的就是单击“ cal.jnlp”文件以运行基本的Web Start计算器。
基本计算器 JavaScript网页 我创建了一个网页来充当计算器。
基本计算器 一个基本的Android计算器。
这是一个使用面向对象的javascript构建的焦点下拉javascript计算器,可以将其附加到网页上的任何输入字段中。 单个网页上可以使用任意数量的实例。
基本计算器
基本计算器一次可以执行一项操作的基本计算器。
启动应用程序: 解压文件 导航到终端中的项目文件夹 安装 凉亭安装 吞咽 Gulp 将在终端窗口中运行 mocha 服务器测试并打开浏览器到计算器应用程序。 计算器应用程序处理: 操作顺序 ...大数的科学记数法
Basic windows calculator replacement for those who likes operator precedence and keyboard input.
Basic calculator element ALU of CPU arry
资源分类:Python库 所属语言:Python 资源全名:T-basic-calculator-0.0.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
<END><br>28 , calc.zip This is a basic calculator written in Visual Basic.<END><br>29 , stopwatch.zip This shows how to count off time in a Stop Watch format.<END><br>31 , taskhide.zip This ...
Calculator Visual Basic 6.0 programming code
Calculator源码,可实现数学计算外,还可以实现一些高级功能,比如公式、平方、正切之类的