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的更多相关文章

  1. (Stack)Basic Calculator I && II

    Basic Calculator I Implement a basic calculator to evaluate a simple expression string. The expressi ...

  2. LeetCode 227. 基本计算器 II(Basic Calculator II)

    227. 基本计算器 II 227. Basic Calculator II 题目描述 实现一个基本的计算器来计算一个简单的字符串表达式的值. 字符串表达式仅包含非负整数,+,-,*,/ 四种运算符和 ...

  3. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  4. LeetCode Basic Calculator II

    原题链接在这里:https://leetcode.com/problems/basic-calculator-ii/ Implement a basic calculator to evaluate ...

  5. Lintcode: Expression Evaluation (Basic Calculator III)

    Given an expression string array, return the final result of this expression Have you met this quest ...

  6. Basic Calculator,Basic Calculator II

    一.Basic Calculator Total Accepted: 18480 Total Submissions: 94750 Difficulty: Medium Implement a bas ...

  7. [LeetCode] Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  8. leetcode 224. Basic Calculator 、227. Basic Calculator II

    这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...

  9. 【LeetCode】227. Basic Calculator II

    Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...

随机推荐

  1. 使用CompletableFuture优化你的代码执行效率

    这篇文章详细讲解java8中CompletableFuture的特性,方法以及实例. 在java8以前,我们使用java的多线程编程,一般是通过Runnable中的run方法来完成,这种方式,有个很明 ...

  2. top 自动执行的shell脚本中,使用top -n 1 > log.txt, 上电自动执行,文件无输出

    . 自动执行的shell脚本中,使用top -n > log.txt, 上电自动执行,文件无输出,使用一下命令解决: //usr/bin/top -d -n -b > log.txt 如果 ...

  3. iOS开发基础-九宫格坐标(5)

    继续在iOS开发基础-九宫格坐标(4)的基础上进行优化. 一.改进思路 1)iOS开发基础-九宫格坐标(4)中 viewDidLoad 方法中的第21.22行对控件属性的设置能否拿到视图类 WJQAp ...

  4. Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

    SpringBoot启动时的异常信息如下: "C:\Program Files\Java\jdk1.8.0_161\bin\java" ......... com.fangxing ...

  5. Centos6.6安装docker

    今天在虚拟机上体验一下docker, 操作系统:Centos6.6 内核版本:2.6 1. https://download.csdn.net/download/dujiaoyang000/10872 ...

  6. 02-JavaScript语法

    JavaScript语法 1.JS的引入 1- 直接在<script>标签下引入 <!DOCTYPE html> <html lang="zh-CN" ...

  7. CodeVs 1615 数据备份

    题目:数据备份 链接:Here 题意:有n个点在一条线上,每次连线可以连接两个点(每个点只能被连一次),要求找出m个连线,他们的和最小(连线权值就是两点距离),输出最小的和.给出n.m和每个点的坐标. ...

  8. Spring Boot的web开发

    web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration 自动配置的ViewResolver 视图的 ...

  9. idea打开项目,没有项目文件,文件报红

    删除项目文件夹中的.idea文件,重启idea,再执行如下操作.

  10. 【数学建模】day14-建立GM(1,1)预测评估模型应用

    学习建立GM(1,1)灰色预测评估模型,解决实际问题: SARS疫情对某些经济指标的影响问题 一.问题的提出 2003 年的 SARS 疫情对中国部分行业的经济发展产生了一定影响,特别是对部分 疫情较 ...