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. python之pickle

    #!/usr/bin/python # -*- coding: UTF- -*- ''' ''' import pickle # pickle 只能Python识别 不适用于别的语言 li = [, ...

  2. 【学习总结】GirlsInAI ML-diary day-14-function函数

    [学习总结]GirlsInAI ML-diary 总 原博github链接-day14 认识函数function 函数相当于一个固定的公式,一个映射.有输入,有输出. 1-python内置函数 max ...

  3. 使用.net core efcore根据数据库结构自动生成实体类

    源码 github,已更新最新代码 https://github.com/leoparddne/GenEntities/ 使用的DB是mysql,所有先nuget一下mysql.data 创建t4模板 ...

  4. springboot使用多数据源以及配置

    1. 首先在application中配置数据源地址 my.datasource.koi.type=com.alibaba.druid.pool.DruidDataSource my.datasourc ...

  5. vue2.0里的路由钩子

    路由钩子 在某些情况下,当路由跳转前或跳转后.进入.离开某一个路由前.后,需要做某些操作,就可以使用路由钩子来监听路由的变化 全局路由钩子: router.beforeEach((to, from, ...

  6. Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块

    StringIO StringIO操作 BytesIO BytesIO操作 file-like对象 路径操作 路径操作模块 3.4版本之前:os.path模块 3.4版本开始 建议使用pathlib模 ...

  7. js和jquery设置css样式的几种方法

    一.js设置样式的方法 1. 直接设置style的属性  某些情况用这个设置 !important值无效 element.style.height = '50px'; 2. 直接设置属性(只能用于某些 ...

  8. ExcelTools使用

    using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using System; using System.Collections.Gen ...

  9. Dijkstra算法——计算一个点到其他所有点的最短路径的算法

    迪杰斯特拉算法百度百科定义:传送门 gh大佬博客:传送门 迪杰斯特拉算法用来计算一个点到其他所有点的最短路径,是一种时间复杂度相对比较优秀的算法 O(n2)(相对于Floyd算法来说) 是一种单源最短 ...

  10. Zabbix通过Orabbix监控Oracle数据库

    一.背景 公司业务使用的是一直Oracle数据库,因为多次出现表空间满的时候不能及时发现,每次都是业务组的人员通知处理,这样下来DBA这边就比较被动,所以老大要求监控表空间剩余大小并且当剩余过小时能够 ...