博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
224. Basic Calculator
阅读量:5297 次
发布时间:2019-06-14

本文共 2425 字,大约阅读时间需要 8 分钟。

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 .

 

Example 1:

Input: "1 + 1"Output: 2

Example 2:

Input: " 2-1 + 2 "Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"Output: 23

 

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

 

Approach #1: Math. [Java]

class Solution {    public int calculate(String s) {        int ret = 0;        Stack
stack = new Stack<>(); int sign = 1; int number = 0; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (Character.isDigit(c)) { number = number * 10 + c - '0'; } else if (c == '-') { ret += number * sign; number = 0; sign = -1; } else if (c == '+') { ret += number * sign; number = 0; sign = 1; } else if (c == '(') { stack.push(ret); stack.push(sign); ret = 0; sign = 1; } else if (c == ')') { ret += number * sign; ret = ret * stack.pop() + stack.pop(); number = 0; sign = 1; } } if (number != 0) ret += number * sign; return ret; }}

  

Analysis:

Simple iterative solution by identifying character one by one. One important thing is that the input is valid, which means the parenthese are always paired and in order.

Only 5 possible input we need to pay attention:

1. digit: it should be one digit from current number.

2. '+': number is over, we can add the the previous number and start a new number.

3. '-': same as above.

4. '(': push the previous result and the sign into the stack, set result to 0, just calculate the new result within the parenthesis.

5. ')': pop out the top two number from stack, first one is the sign before this pair of parenthesis, second is the temporary reslut before this pair of parenthesis. We add them together.

Finally if there is only one number, from the above solution, we haven't add the number to the result, so we do a check see if the number is zero.

 

Reference:

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10804664.html

你可能感兴趣的文章
第二章ARP——地址解析协议
查看>>
BIO模型
查看>>
前端开发 --- CSS参考手册
查看>>
认识迅雷界面引擎
查看>>
/* 搜索文件的method */
查看>>
Pandas_实现数字顺序填充、指定值交替填充、日期顺序填充(按日、月、年)
查看>>
第八章博客
查看>>
解决input为number类型时maxlength无效的问题
查看>>
使用C#加密及解密字符串
查看>>
MYSQL 5.7 新增150多个新功能
查看>>
UE导航系统详
查看>>
软件测试作业3
查看>>
环境准备—之—linux下安装jdk
查看>>
VB类的应用
查看>>
贪吃蛇
查看>>
NSMutableAttributedString 的使用方法,设置格式
查看>>
php中的可变变量、可变函数、匿名函数
查看>>
jdk8+Mybatis3.5.0+Mysql读取LongBlob失败
查看>>
[Ubuntu] 如何解压有乱码的zip文件
查看>>
如何让浮动的元素换行??css
查看>>