-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCalculator
More file actions
67 lines (65 loc) · 1.87 KB
/
Calculator
File metadata and controls
67 lines (65 loc) · 1.87 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Calculator
Send Feedback
Given a String s, consisting of non negative integers and +,- operators as well as brackets ( and ).
Your task is to solve the given string and print the output.
Input Format:
First and only line contains the string s.
Output Format:
Print the result of the given string.
Constraints:
1 <= String length <= 20000
Sample Input 1:
(1+2)
Sample Output 1:
3
Sample Input 2:
(1+(4+5+2)-3)+(6+8)
Sample Output 2:
23
code in java ***********************************************
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main (String[] args) {
// Write your code here
// Take input and print desired output
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(calculate(s));
}
public static int calculate(String s) {
if (s == null || s.isEmpty()) return 0;
final int N = s.length();
Deque<Integer> stack = new ArrayDeque<>();
int res = 0, num = 0, sign = 1;
for (int i = 0; i < N; i++) {
char ch = s.charAt(i);
if (ch == ' ') {
continue;
} else if (ch <= '9' && ch >= '0') {
num = ch - '0' + num * 10;
} else if (ch == '+') {
res += sign * num;
num = 0;
sign = 1;
} else if (ch == '-') {
res += sign * num;
num = 0;
sign = -1;
} else if (ch == '(') {
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
num = 0;
} else if (ch == ')') {
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
}
return res + sign * num;
}
}