978. Basic Calculator

https://www.lintcode.com/problem/basic-calculator/description

public class Solution {
/**
* @param s: the given expression
* @return: the result of expression
*/
public int calculate(String s) {
// Write your code here
Stack<Integer> stack = new Stack<Integer>();
int result =0;
int number =0;
int sign =1; for(int i =0;i<s.length();i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
number = 10*number + (int)(c-'0');
}else if(c=='+'){
result +=sign*number;
number =0;
sign =1;
}else if(c == '-'){
result += sign * number;
number = 0;
sign = -1;
}else if(c == '('){
stack.push(result);
stack.push(sign);
sign = 1;
result = 0;
}else if(c == ')'){
result += sign* number;
number =0;
result*=stack.pop();
result+=stack.pop();
}
} if(number!=0){
result +=sign*number;
} return result;
}
}

980. Basic Calculator II

https://www.lintcode.com/problem/basic-calculator-ii/description

public class Solution {
/**
* @param s: the given expression
* @return: the result of expression
*/
public int calculate(String s) {
// Write your code here
if(s==null || s.length()==0){
return 0;
} int len = s.length();
Stack<Integer> stack = new Stack<Integer>();
int num =0;
char sign = '+';
for(int i =0;i<len;i++){ if(Character.isDigit(s.charAt(i))){
num = num*10 + s.charAt(i)-'0';
} if((!Character.isDigit(s.charAt(i)) && ' '!=s.charAt(i)) ||i==len-1){
if(sign =='-'){
stack.push(-num);
}
if(sign == '+'){
stack.push(num);
}
if(sign == '*'){
stack.push(stack.pop()*num);
}
if(sign == '/'){
stack.push(stack.pop()/num);
}
sign = s.charAt(i);
num =0;
}
} int re =0;
for(int i:stack){
re +=i;
}
return re; } }

849. Basic Calculator III

https://www.lintcode.com/problem/basic-calculator-iii/description

public class Solution {
/**
* @param s: the expression string
* @return: the answer
*/
public int calculate(String s) {
// Write your code here
if(s==null || s.length()==0){
return 0;
} Stack<Integer> nums = new Stack<Integer>();
Stack<Character> opr = new Stack<Character>(); int num =0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c==' '){
continue;
}
if(Character.isDigit(c)){
num = c-'0';
while(i<s.length()-1 && Character.isDigit(s.charAt(i+1))){
num = num*10+ (s.charAt(i+1)-'0');
i++;
}
nums.push(num);
num =0;
}else if(c=='('){
opr.push(c);
}else if(c==')'){
while(opr.peek()!='('){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.pop();
}else if(c=='+'||c=='-'||c=='*'||c=='/'){
if(!opr.isEmpty()&&needCalFirst(opr.peek(),c)){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.push(c);
}
} while(!opr.isEmpty()){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
} return nums.pop();
} public int calculate(int num1, int num2, char op){
switch(op){
case '+':return num2+num1;
case '-':return num2-num1;
case '*':return num2*num1;
case '/':return num2/num1;
default:return 0;
}
} public boolean needCalFirst(char firstOp, char secondOp){
if(firstOp=='('|| firstOp==')'){
return false;
} if((firstOp=='+'||firstOp=='-')&&(secondOp=='*'||secondOp=='/')){
return false;
} return true;
}
}

368. Expression Evaluation

https://www.lintcode.com/problem/expression-evaluation/description?_from=ladder&&fromId=4

同849 只需注意输入可能不是一个可计算表达式 eg:{'(',')'}

public class Solution {
/**
* @param expression: a list of strings
* @return: an integer
*/
public int evaluateExpression(String[] expression) {
// write your code here
if(expression==null || expression.length==0){
return 0;
} String s = "";
for(int i=0;i<expression.length;i++){
s+=expression[i];
} Stack<Integer> nums = new Stack<Integer>();
Stack<Character> opr = new Stack<Character>(); int num =0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c==' '){
continue;
}
if(Character.isDigit(c)){
num = c-'0';
while(i<s.length()-1 && Character.isDigit(s.charAt(i+1))){
num = num*10+ (s.charAt(i+1)-'0');
i++;
}
nums.push(num);
num =0;
}else if(c=='('){
opr.push(c);
}else if(c==')'){
while(opr.peek()!='('){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.pop();
}else if(c=='+'||c=='-'||c=='*'||c=='/'){
if(!opr.isEmpty()&&needCalFirst(opr.peek(),c)){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.push(c);
}
} while(!opr.isEmpty()){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
} if(nums.size()>0){
return nums.pop();
} return 0;
} public int calculate(int num1, int num2, char op){
switch(op){
case '+':return num2+num1;
case '-':return num2-num1;
case '*':return num2*num1;
case '/':return num2/num1;
default:return 0;
}
} public boolean needCalFirst(char firstOp, char secondOp){
if(firstOp=='('|| firstOp==')'){
return false;
} if((firstOp=='+'||firstOp=='-')&&(secondOp=='*'||secondOp=='/')){
return false;
} return true;
}
}

Basic Calculator - Stack(表达式计算器)的更多相关文章

  1. LeetCode OJ:Basic Calculator(基础计算器)

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

  2. [LeetCode] 227. Basic Calculator II 基本计算器 II

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

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

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

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

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

  5. [LeetCode] Basic Calculator IV 基本计算器之四

    Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...

  6. 227 Basic Calculator II 基本计算器II

    实现一个基本的计算器来计算一个简单的字符串表达式. 字符串表达式仅包含非负整数,+, - ,*,/四种运算符和空格 . 整数除法仅保留整数部分. 你可以假定所给定的表达式总是有效的. 一些例子: &q ...

  7. [LeetCode] 224. Basic Calculator 基本计算器

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

  8. [LeetCode] Basic Calculator 基本计算器

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

  9. [Swift]LeetCode224. 基本计算器 | Basic Calculator

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

随机推荐

  1. asp.net 4高级程序设计( 第4版)文摘

    第一部分 核心概念 第1章 asp.net 简介 第2章 visual studio 第3章 Web窗体 3.2 web窗体处理阶段 页面框架初始化(page.init),用户代码初始化(page.l ...

  2. mysql 开通远程连接

    使用localhost好用,但是改成ip地址后不好用,执行sql语句做如下修改: update user set host = '%' where user = 'root'; flush privi ...

  3. swift -pop的简单动画

    //1.新建空文件  命名Podfile //2.写入 pod ‘pop’,’~>1.0’  保存 //3.打开终端,进入项目路径 执行pod install //4.新建桥接头文件 导入#im ...

  4. InstaGAN: Instance-Aware Image-to-Image Translation

  5. idea jvm 优化

    修改对应配置文件 64位的是idea64.exe.vmoptions -Xms2048m -Xmx2048m -Xmn1024m -XX:PermSize=512m -XX:MaxPermSize=5 ...

  6. 企业搜索引擎开发之连接器connector(二十)

    连接器里面衔接数据源与数据推送对象的是QueryTraverser类对象,该类实现了Traverser接口 /** * Interface presented by a Traverser. Used ...

  7. Github 的注册教程和初步使用体验

    我叫许晴,是网工143的学生,学号是1413042064,兴趣包括手绘,看书和手游.学习过c++和汇编语言课程,但在编程方面没什么独立实践经验. 我的Githup用户名是 XQ123 .下面是我在gi ...

  8. Default style sheet for HTML 4

    http://www.w3.org/TR/CSS21/sample.html html, address, blockquote, body, dd, div, dl, dt, fieldset, f ...

  9. C# 使用 COALESCE 表达式简化 Null 检查

    下面这个判断 null 的语句: a == null ? b: a 可以用 COALESCE 表达式,简化成: a ?? b

  10. NET npoi 合并单元值处理

    获取sheet中存在合并单元格总数,循环绑定值 // 得到一个sheet中有多少个合并单元格 int sheetMergeCount = sheet.NumMergedRegions; ; i < ...