DEV Community

Debesh P.
Debesh P.

Posted on

224. Basic Calculator | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/basic-calculator/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/basic-calculator/solutions/7576826/most-optimal-beats-100-all-languages-sta-jd4n


leetcode 224


Solution

class Solution {
    public int calculate(String s) {

        Stack<Integer> stack = new Stack<>();

        int res = 0;
        int curr = 0;
        int sign = 1;

        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                curr = curr * 10 + (c - '0');
            } else if (c == '+') {
                res += curr * sign;
                sign = 1;
                curr = 0;
            } else if (c == '-') {
                res += curr * sign;
                sign = -1;
                curr = 0;
            } else if (c == '(') {
                stack.push(res);
                stack.push(sign);
                res = 0;
                sign = 1;
                curr = 0;
            } else if (c == ')') {
                res += curr * sign;
                curr = 0;
                res *= stack.pop();
                res += stack.pop();
            }
        }

        res += sign * curr;
        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)