Skip to content

Commit 6fc15c1

Browse files
Tushar RoyTushar Roy
authored andcommitted
basic calculator leetcode
1 parent fb541ee commit 6fc15c1

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.interview.number;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* Date 10/11/2016
7+
* @author Tushar Roy
8+
*
9+
* Implement a basic calculator to evaluate a simple expression string.
10+
* The expression string contains only non-negative integers, +, -, *, / operators and empty spaces.
11+
* The integer division should truncate toward zero.
12+
*
13+
* Time complexity O(n)
14+
* Space complexity (n)
15+
*
16+
* https://leetcode.com/problems/basic-calculator-ii/
17+
*/
18+
public class BasicCalculator {
19+
public int calculate(String s) {
20+
Stack<Integer> operand = new Stack<>();
21+
int current = 0;
22+
char prevOperator = '+';
23+
for (int i = 0; i < s.length(); i++) {
24+
char ch = s.charAt(i);
25+
if (Character.isDigit(ch)) {
26+
current = current * 10 + ch - '0';
27+
}
28+
//if its not a digit or space then go in this block.
29+
//also if it is last character then go in this block and finish up last operation.
30+
if (i == s.length() - 1 || (ch != ' ' && !Character.isDigit(ch))) {
31+
if (prevOperator == '+') {
32+
operand.push(current);
33+
} else if (prevOperator == '-') {
34+
operand.push(-current);
35+
} else if (prevOperator == '/') {
36+
operand.push(operand.pop() / current);
37+
} else {
38+
operand.push(operand.pop() * current);
39+
}
40+
prevOperator = ch;
41+
current = 0;
42+
}
43+
}
44+
int result = 0;
45+
while (!operand.isEmpty()) {
46+
result += operand.pop();
47+
}
48+
return result;
49+
}
50+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.interview.number;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class BasicCalculatorTest {
7+
8+
@Test
9+
public void testDifferentCases() {
10+
BasicCalculator basicCalculator = new BasicCalculator();
11+
Assert.assertEquals(0, basicCalculator.calculate("0"));
12+
Assert.assertEquals(9, basicCalculator.calculate("0 + 9"));
13+
Assert.assertEquals(19, basicCalculator.calculate("1 + 9 * 2"));
14+
Assert.assertEquals(15, basicCalculator.calculate("3 + 9/2 * 3"));
15+
Assert.assertEquals(6, basicCalculator.calculate("8 -2 + 3/ 5 "));
16+
17+
}
18+
}

0 commit comments

Comments
 (0)