-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculator.java
More file actions
45 lines (39 loc) · 1.45 KB
/
Copy pathBasicCalculator.java
File metadata and controls
45 lines (39 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Stack;
public class BasicCalculator {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int number = 0;
char operation = '+';
s = s.replaceAll("\\s", ""); // Remove all whitespaces
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
number = number * 10 + (c - '0'); // Form the number
}
if (!Character.isDigit(c) || i == s.length() - 1) {
if (operation == '-') {
stack.push(-number);
} else if (operation == '+') {
stack.push(number);
} else if (operation == '*') {
stack.push(stack.pop() * number);
} else if (operation == '/') {
stack.push(stack.pop() / number);
}
// due to this code will correctly handle sequences of numbers and operations in the input string
operation = c;
number = 0;
}
}
int result = 0;
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
public static void main(String[] args) {
BasicCalculator calculator = new BasicCalculator();
String expression = "3+2*2";
System.out.println("Result: " + calculator.calculate(expression)); // Output: 7
}
}