FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/BasicCalculatorIII.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
BasicCalculatorIII.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (51 loc) · 1.68 KB
Breadcrumbs
coding-Interview
/
BasicCalculatorIII.java
Copy path
File metadata and controls
57 lines (51 loc) · 1.68 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
com
.
leetcode
;
import
java
.
util
.
LinkedList
;
import
java
.
util
.
Queue
;
import
java
.
util
.
Stack
;
public
class
BasicCalculatorIII
{
//https://leetcode.com/problems/basic-calculator-iii/
class
Solution
{
public
int
calculate
(
String
s
) {
Queue
<
Character
>
queue
=
new
LinkedList
<>();
for
(
char
c
:
s
.
toCharArray
()){
queue
.
offer
(
c
);
}
queue
.
offer
(
'+'
);
return
calculateQueue
(
queue
);
}
public
int
calculateQueue
(
Queue
<
Character
>
queue
){
int
result
=
0
;
int
op
=
'+'
;
int
num
=
0
;
Stack
<
Integer
>
stack
=
new
Stack
<>();
while
(
queue
.
size
() >
0
){
char
ch
=
queue
.
poll
();
if
(
ch
==
' '
)
continue
;
if
(
Character
.
isDigit
(
ch
)){
num
=
num
*
10
+
ch
-
'0'
;
}
else
if
(
ch
==
'('
){
num
=
calculateQueue
(
queue
);
//caclulate and update num
}
else
if
(!
Character
.
isDigit
(
ch
)){
if
(
op
==
'+'
){
stack
.
push
(
num
);
}
else
if
(
op
==
'-'
){
stack
.
push
(-
num
);
}
else
if
(
op
==
'*'
){
stack
.
push
(
stack
.
pop
() *
num
);
}
else
if
(
op
==
'/'
){
stack
.
push
(
stack
.
pop
() /
num
);
}
op
=
ch
;
num
=
0
;
}
if
(
ch
==
')'
){
break
;
}
}
while
(
stack
.
size
() >
0
){
result
+=
stack
.
pop
();
}
return
result
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL