LeetCode:Basic Calculator

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Basic Calculator相关的知识,希望对你有一定的参考价值。

Basic Calculator




Total Accepted: 29148 Total Submissions: 128464 Difficulty: Hard

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.

Subscribe to see which companies asked this question

Hide Tags
 Stack Math

























java code:

public class Solution {
    public int calculate(String s) {
        
        Stack<Integer> stack = new Stack<Integer>();
        
        int result = 0;
        int sign = 1;
        int n = s.length();
        
        for(int i=0;i<n;i++) {
            
            char c = s.charAt(i);
            if(Character.isDigit(c)) {
                int sum = c-'0';
                while(i+1<n && Character.isDigit(s.charAt(i+1))) {
                    sum = 10*sum + s.charAt(i+1)-'0';
                    i++;
                }
                result += sign * sum;
            } else if(c=='+') {
                sign = 1;
            } else if(c=='-') {
                sign = -1;
            } else if(c=='(') {
                stack.push(result);
                stack.push(sign);
                sign = 1;
                result = 0;
            } else if(c==')') {
                result = result * stack.pop() + stack.pop();
            }
        }
        
        return result;
    }
}


以上是关于LeetCode:Basic Calculator的主要内容,如果未能解决你的问题,请参考以下文章

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

Arcgis中用raster calculator怎样 计算山的顶点,应怎样编写

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:Calculator.main 中的 0(Calculator.java:25)[重复]

typescript 开发人员日记:第1天 - packages / server / src / calculator / calculator.ts

LeetcodeBasic Calculator

LeetcodeBasic Calculator II