Last updated on October 6th, 2024 at 02:01 pm
Here, We see Basic Calculator LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Math, Stack
Companies
Level of Question
Hard
Basic Calculator LeetCode Solution
Table of Contents
Problem Statement
Given a string s
representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Example 1:
Input: s = “1 + 1”
Output: 2
Example 2:
Input: s = ” 2-1 + 2 ”
Output: 3
Example 3:
Input: s = “(1+(4+5+2)-3)+(6+8)”
Output: 23
1. Basic Calculator Solution C++
class Solution { public: int calculate(string s) { int total = 0; vector<int> signs(2, 1); for (int i=0; i<s.size(); i++) { char c = s[i]; if (c >= '0') { int number = 0; while (i < s.size() && s[i] >= '0') number = 10 * number + s[i++] - '0'; total += signs.back() * number; signs.pop_back(); i--; } else if (c == ')') signs.pop_back(); else if (c != ' ') signs.push_back(signs.back() * (c == '-' ? -1 : 1)); } return total; } };
2. Basic Calculator Solution Java
class Solution { public int calculate(String s) { 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; } }
3. Basic Calculator Solution JavaScript
var calculate = function(s) { let sign = 1, sum = 0; const stack = []; for (let i = 0; i < s.length; i += 1) { if (s[i] >= '0' && s[i] <= '9') { let num = 0 while (s[i] >= '0' && s[i] <= '9') { num = (num * 10) + (s[i] - '0'); i += 1; } sum += (num * sign); i -= 1; } else if (s[i] === '+') { sign = 1; } else if (s[i] === '-') { sign = -1; } else if (s[i] === '(') { stack.push(sum); stack.push(sign); sum = 0 sign = 1; } else if (s[i] === ')') { sum = stack.pop() * sum; sum += stack.pop(); } } return sum; };
4. Basic Calculator Solution Python
class Solution(object): def calculate(self, s): total = 0 i, signs = 0, [1, 1] while i < len(s): c = s[i] if c.isdigit(): start = i while i < len(s) and s[i].isdigit(): i += 1 total += signs.pop() * int(s[start:i]) continue if c in '+-(': signs += signs[-1] * (1, -1)[c == '-'], elif c == ')': signs.pop() i += 1 return total