Basic Calculator II
Given a string s
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]
Note:
You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
Example 1
Output: 7
Example 2
Output: 1
Example 2
Output: 5
Constraints:
1 <= s.length <= 3 * 105 consists of integers and operatorss separated by some number of spaces.('+', '-', '*', '/') represents a valid expression.s- All the integers in the expression are non-negative integers in the range
.[0, 231 - 1] - The answer is guaranteed to fit in a 32-bit integer.
Solution 1 - Using a stack and loop over digits and operands in input string
In this approach, we will use a Stack+-*/
Implementation steps:
-
We will create two variables
to capture digits as we loop through stringnumber , ands to track the operator. We will initializesign , the reason we do this is because, say for example input string issign = '+' for number"10-2*3+5/2" in the beginning it wil default to10 sign.+ -
We will also create a
for tracking current operands as we will loop through input string.Stack -
Then, we will loop through characters of input string
:s
If the character is digit 0 -9 :
-
Read the character and add it to the
, when adding a new character into number we need ensure that the position of the numebr is correct. We can do it as follows, multiply current numebr withnumber and add new digit, for example the number is10 , first we will read"79" , then when adding we will do it as7 that converts string "79" to integer7*10 + 9 .79Javanumber = number *10 + (current - '0');Note: If you dont want to do it this way, you can keep appending the number as string and when it's needed to convert to integer, use
method.Integer.parseInt
If the character is an operator or the ending character of input:
-
If the sign is
, then add the+ to thenumber .stack -
If the sign is
, then add the- to the-number .stack -
If the sign is
, then take the last number from the* and multiply withstack and add the result tonumber .stack -
If the sign is
, then take the last number from the/ and divide bystack and add the result tonumber .stack -
Once added to the stack, update the
variable with current sign and reset thesign .number -
Now the stack contains numbers after applying
and* operations from above steps, now we can simply loop over the stack and return the sum of the numbers./
Example:
Let's take an example s = "10-2*3+5/2"
-
First initialize the variables
,number = 0 , and an emptysign = '+' .Stack -
Then, loop through characters of input string:
-
1st character is
, we will append this to number1 , this will becomenumber = number * 10 + ('1' -'0') .number = 0*10 + 1-0 = 1 -
2nd character is
, we will append this to number, it will become0 .number = 1 *10 + 0-0 = 10 -
3rd character is an operator
, so we will check the current value that- holding, which issign , so we add current number+ to the10 and updatestack and resetsign = '-' .number = 0stack 10 -
4th character is
, so we will add it to2 , it will become 2.number -
5th character is an operator
, so we will check the current value that* holding, which issign , so we add current number with - sign- to the-2 and updatestack and resetsign = '*' .number = 0stack -2 10 -
6th character is
, so we will add it to3 , it will become 3.number -
7th character is an operator
, so we will check the current value that+ holding, which issign , so we take latest from stack, multiply with current number, and add it back to* . So, top number fromstack isstack and current number is-2 , so we will add3 to the stack and update-6 and resetsign = '+' .number = 0stack -6 10 -
8th character is
, so we will add it to5 , it will become 5.number -
9th character is an operator
, so we will check the current value that/ holding, which issign , so we will add+ to the stack and update5 and resetsign = '/' .number = 0stack 5 -6 10 -
10th character is the last character
, so we take latest from stack, divide by current number, and add it back to2 . So, top number fromstack isstack and current number is5 , so we will add2 to the stack.5 /2 = 2stack 2 -6 10
-
1st character is
-
Now, we will go through the
and add them up,stack , that is our answer.2 - 6 + 10 = 6
import java.util.Stack;
public class BasicCalculatorII {
static int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int number = 0;
char sign = '+'; // reason we are using this is say if the input is "10-2*3+5/2"
// assume + is default sign for 10, if the starting is -10 for example, then it will 0+ at the beginning.
for(int i=0; i<s.length(); i++) {
char current = s.charAt(i);
if(Character.isDigit(current)) { // If the character is between 0-9
number = number *10 + (current - '0'); // number *10 is to concatenate the number,
// say if the input is two digit letter,
// for example, 79 first we take 7, then when we get 9 we have to move 7 to 10th position,
// so we multiply with 10, then add current number.
}
if( (!Character.isDigit(current) && current != ' ')
|| i == s.length() -1 ) {
if(sign == '+') {
stack.push(number);
} else if(sign == '-') {
stack.push(-number);
} else if (sign == '*') {
stack.push(stack.pop() * number);
} else if (sign == '/') {
stack.push(stack.pop() / number);
}
sign = current;
number = 0;
}
}
int result = 0;
while(!stack.isEmpty()) {
result+=stack.pop();
}
return result;
}
public static void main(String[] args) {
System.out.println(calculate("3+5 / 2 "));
System.out.println(calculate("10-2*3+5/2"));
System.out.println(calculate("-10-2*3+5/2"));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where ns
Space complexity: O(n) for the Stack
Above implementations source code can be found at