# Basic Calculator II LeetCode Solution

Here, We see Basic Calculator II problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

## Problem Statement ->

Given a string which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 – 1].

```Example 1:
Input: s = "3+2*2"
Output: 7

Example 2:
Input: s = " 3/2 "
Output: 1

Example 3:
Input: s = " 3+5 / 2 "
Output: 5```

## Basic Calculator II Leetcode Solution C++ ->

``````class Solution {
public:
int calculate(string s) {
istringstream in('+' + s + '+');
long long total = 0, term = 0, n;
char op;
while (in >> op) {
if (op == '+' or op == '-') {
total += term;
in >> term;
term *= 44 - op;
} else {
in >> n;
if (op == '*')
term *= n;
else
term /= n;
}
}
}
};
```Code language: C++ (cpp)```

## Basic Calculator II Leetcode Solution Java ->

``````class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) return 0;
int num = 0, tmp = 0, res = 0;
char op = '+';
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
tmp = tmp*10 + c - '0';
} else if (c != ' ') {
//process the numerical value of string so far; based on what 'op' we have before it
num = cal(num, tmp, op);
if (c == '+' || c == '-') {
res += num;
num = 0;
}
// reset
tmp = 0;
op = c;
}
}
return res + cal(num, tmp, op);
}
private int cal(int num, int tmp, char op) {
if (op == '+') return num + tmp;
else if (op == '-') return num - tmp;
else if (op == '*') return num * tmp;
else    return num / tmp;
}
}
```Code language: Java (java)```

## Basic Calculator II Leetcode Solution JavaScript ->

``````var calculate = function(s) {
let stack = [];
let num = '';
let sign = null
// we loop till the full length of the array to account for last sign
for(let i = 0; i <= s.length; i++){
const curr = s[i];
//handle space
if(curr === ' ') continue;
//if char is a number
if(!isNaN(curr)) num+=curr;
//if we have a  sign + - / *
if(isNaN(curr)){
num = Number(num)
switch(sign){
case '+':
case null:
//we push the initial number into the stack
stack.push(num)
break;
case '-':
//we push any values after the subtraction sign as negative
stack.push(-num)
break;
case '*':
//we pop the stack then multiply and push back
stack.push(stack.pop()*num)
break;
case '/':
//we pop the stack then devide and push back
stack.push(parseInt(stack.pop()/num, 10))
break;
}
// sign becomes current sign
sign = curr;
// we reset num
num = '';
}
}
//we reduce the array adding positive and negative numbers
return stack.reduce((a,b)=>{
return a+b
},0)
};
```Code language: JavaScript (javascript)```

## Basic Calculator II Leetcode Solution Python ->

``````class Solution:
def calculate(self, s: str) -> int:
num = 0
res = 0
pre_op = '+'
s+='+'
stack = []
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c == ' ':
pass
else:
if pre_op == '+':
stack.append(num)
elif pre_op == '-':
stack.append(-num)
elif pre_op == '*':
operant = stack.pop()
stack.append((operant*num))
elif pre_op == '/':
operant = stack.pop()
stack.append(math.trunc(operant/num))
num = 0
pre_op = c
return sum(stack)
```Code language: Python (python)```

#### Permutations II LeetCode Solution

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in…

#### Reverse Bits LeetCode Solution

Reverse bits of a given 32 bits unsigned integer.

#### Find First and Last Position of Element in Sorted Array LeetCode Solution

Given an array of integers nums sorted in non-decreasing order, find the starting and ending…

#### Two Sum LeetCode Solution

Given an array of integers nums and an integer target, return indices of the two…

#### Combination Sum II LeetCode Solution

Given a collection of candidate numbers (candidates) and a target number (target), find all unique…

#### Text Justification LeetCode Solution

Given an array of strings words and a width maxWidth, format the text such that each line has…
Scroll to Top