Basic Calculator I && II && III
Basic Calculator I
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.
分析:这题因为不存在乘法和除法,所以,对于里面的减号,我们可以把它当成+(-num)来处理。所以,每次遇到一个数字的时候,我们需要知道这个数字的符号,每当我们把这个数字所有的digit都拿到以后,就可以得到这个数,然后把这个数加到之前的临时结果里。
对于比较特殊的处理是括号,但是这里有一个很巧的思路,我们可以把括号里的表达式call当前的方法来计算。
class Solution {
public int calculate(String s) {
int res = , num = , sign = , n = s.length();
for (int i = ; i < n; ++i) {
char c = s.charAt(i);
if (c >= '' && c <= '') {
num = * num + (c - '');
} else if (c == '(') {
int j = i, cnt = ;
for (; i < n; ++i) {
char letter = s.charAt(i);
if (letter == '(') ++cnt;
if (letter == ')') --cnt;
if (cnt == ) break;
}
num = calculate(s.substring(j + , i));
}
if (c == '+' || c == '-' || i == n - ) {
res += sign * num;
num = ;
sign = (c == '+') ? : -;
}
}
return res;
}
}
Basic Calculator II
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
分析:因为没有括号,所以我们可以把加或者减的部分当成一个数,比如 5-2,把它当成(5)+(-2)。同理,对于有乘或者除,或者既有乘又有除的话,也把它当成一个数,比如5-3*2/4=(5)-(3*2/4)。对于乘法和除法,我们总是从左算到右,所以我们可以把* or /之前的部分先存下来,当符号是 * or /的时候,再取出来就可以了。
注意:我们处理的时候,总是处理之前一个符号,而不是当前符号
class Solution {
public int calculate(String s) {
int res = , num = , n = s.length();
char op = '+';
Stack<Integer> st = new Stack<>();
for (int i = ; i < n; ++i) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
num = num * + ch - '';
} else if (isOperator(ch)) {
addToStack(op, num, st);
op = ch;
num = ;
}
}
// handle last case
addToStack(op, num, st);
while (!st.empty()) {
res += st.pop();
}
return res;
} private boolean isOperator(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
return true;
}
return false;
} private void addToStack(char op, int num, Stack<Integer> st) {
if (op == '+') st.push(num);
if (op == '-') st.push(-num);
if (op == '*' || op == '/') {
int tmp = (op == '*') ? st.pop() * num : st.pop() / num;
st.push(tmp);
}
}
}
Basic Calculator III
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-negativeintegers and empty spaces .
The expression string contains only non-negative integers, +
, -
, *
, /
operators , open (
and closing parentheses )
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647]
.
Some examples:
"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12
Note: Do not use the eval
built-in library function.
分析:只要把括号部分的处理加进来就可以了。
class Solution {
public int calculate(String s) {
int res = , num = , n = s.length();
char op = '+';
Stack<Integer> st = new Stack<>();
for (int i = ; i < n; ++i) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
num = num * + ch - '';
} else if (ch == '(') {
int j = i, cnt = ;
for (; i < n; ++i) {
char letter = s.charAt(i);
if (letter == '(') ++cnt;
if (letter == ')') --cnt;
if (cnt == ) break;
}
num = calculate(s.substring(j + , i));
} else if (isOperator(ch)) {
addToStack(op, num, st);
op = ch;
num = ;
}
}
// handle last case
addToStack(op, num, st);
while (!st.empty()) {
res += st.pop();
}
return res;
} private static boolean isOperator(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
return true;
}
return false;
} private static void addToStack(char op, int num, Stack<Integer> st) {
if (op == '+') st.push(num);
if (op == '-') st.push(-num);
if (op == '*' || op == '/') {
int tmp = (op == '*') ? st.pop() * num : st.pop() / num;
st.push(tmp);
}
}
}
Basic Calculator I && II && III的更多相关文章
- (Stack)Basic Calculator I && II
Basic Calculator I Implement a basic calculator to evaluate a simple expression string. The expressi ...
- LeetCode 227. 基本计算器 II(Basic Calculator II)
227. 基本计算器 II 227. Basic Calculator II 题目描述 实现一个基本的计算器来计算一个简单的字符串表达式的值. 字符串表达式仅包含非负整数,+,-,*,/ 四种运算符和 ...
- [LeetCode] Basic Calculator II 基本计算器之二
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- LeetCode Basic Calculator II
原题链接在这里:https://leetcode.com/problems/basic-calculator-ii/ Implement a basic calculator to evaluate ...
- Lintcode: Expression Evaluation (Basic Calculator III)
Given an expression string array, return the final result of this expression Have you met this quest ...
- Basic Calculator,Basic Calculator II
一.Basic Calculator Total Accepted: 18480 Total Submissions: 94750 Difficulty: Medium Implement a bas ...
- [LeetCode] Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- leetcode 224. Basic Calculator 、227. Basic Calculator II
这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...
- 【LeetCode】227. Basic Calculator II
Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...
随机推荐
- 【Api】easy-mock在线api
解决 在使用easy-mock模拟post提交数据的情况中,我们有时需要对提交的数据进行简单逻辑处理.查阅文档发现可以使用"_req.body.keyname"来获取相应的值,但是 ...
- Django缓存机制--rest_framework中节流源码使用的就是django提供的缓存api
一.配置缓存 https://www.jb51.net/article/124434.htm 二.缓存全站.页面.局部 三.自我控制的简单缓存API API 接口为:django.core.c ...
- 有关python2与python3中关于除的不同
有关python2与python3中关于除的不同 python中2版本与3版本关于除的处理还是有一些差异的. 在python 2.7.15中除(/)是向下取整的,即去尾法. 123/10 # 结果 1 ...
- 控制结构(6): 最近最少使用(LRU)
// 上一篇:必经之地(using) // 下一篇:程序计数器(PC) 基于语言提供的基本控制结构,更好地组织和表达程序,需要良好的控制结构. There are only two hard thin ...
- Java的selenium代码随笔(5)
//以下七种方法主要用于生成年.月.日.小时.分钟和秒的信息,用于生成保存截图的文件目录名和文件名/** 格式化输出日期* * @return 返回字符型日期*/public static Strin ...
- Linux(Ubuntu 16) 下Java开发环境的配置(一)------JDK的配置
前言: 本文介绍的是通用的安装方法,一般linux系统均可使用该方法安装.本文以Java8环境为例进行配置. 1.JDK的下载 进入java下载页(http://www.oracle.com/te ...
- SharedPreferences类的使用
SharedPreferences,用xml文件保存用户的偏好设置,是一个轻量级的存储类. 效果图: 代码: activity_main <?xml version="1.0" ...
- iOS发布证书申请
一. 准备工作1.1.准备打包服务器 打包服务器搭建详见http://bbs.justep.com/thread-67724-1-1.html 或 http://www.cnblogs.com/Wo ...
- IO多路复用和local概念
一.local 在多个线程之间使用threading.local对象,可以实现多个线程之间的数据隔离 import time import random from threading import T ...
- java并发编程实践——王宝令(极客时间)学习笔记
1.并发 分工:如何高效地拆解任务并分配给线程 同步:线程之间如何协作 互斥:保证同一时刻只允许一个线程访问共享资源 Fork/Join 框架就是一种分工模式,CountDownLatch 就是一种典 ...