Basic Calculator - Stack(表达式计算器)

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;
    }
}

原文地址:https://www.cnblogs.com/lizzyluvcoding/p/10772635.html

时间: 2024-08-29 11:35:49

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

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

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

basic calculator (stack problem)

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

解题报告:LeetCode Basic Calculator(简单计算器)

题目出处:https://leetcode.com/problems/basic-calculator/题意描述: 给定一个只含加减号,括号,空格和非负数的合法字符串,在不调用库函数eval的条件下求出其值 解决思路: 由于此题只有加减号,因此不存在运算符优先级的问题,只需要稍微注意一下括号即可. 因此,可以用两个栈ops,numbers来分别存储未处理的运算符和未处理的数字,并对字符串进行一次扫描.对于对于扫描到的任意字符是s[i],做如下处理: 若s[i]为空格,则继续扫描. 若s[i]为左

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

Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1}(given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as [

表达式计算器类的设计5(面向对象的表达式计算器8)

计算器的github下载地址:https://github.com/ljian1992/calculator 概述 表达式计算器的类基本已经设计完成了,由于在程序运行的时候总会有这样那样的异常,例如:a +2, a没有初始化,对于异常的管理一般而言是需要自定义异常类.这个自定义异常类也是在继承了系统已经定义好的exception类,然后再重新定义内容. 异常的种类 语法异常---->SyntaxError类 赋值时左操作数不是变量:1 = 2; 缺少括号:1 + (2*2 不认识的函数: 函数缺

[Swift]LeetCode227. 基本计算器 II | 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. Example 1: Input: "3+2*2" Ou

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

227. 基本计算器 II 227. Basic Calculator II 题目描述 实现一个基本的计算器来计算一个简单的字符串表达式的值. 字符串表达式仅包含非负整数,+,-,*,/ 四种运算符和空格.整数除法仅保留整数部分. LeetCode227. Basic Calculator II中等 示例?1: 输入: "3+2*2" 输出: 7 示例 2: 输入: " 3/2 " 输出: 1 示例 3: 输入: " 3+5 / 2 " 输出:

Basic Calculator 基本计算器-Leetcode

1.题目: 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 expressi

227. 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. Example 1: Input: "3+2*2&q