Skip to content

Commit 3fe6722

Browse files
committed
new
1 parent 7d0aa97 commit 3fe6722

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ Leetcode solutions in Java and Python
33

44
|#|Title|Solution|Difficulty|
55
|---|-----|--------|----------|
6+
|227|[Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)|[Java](./src/basic_calculator_ii)|Medium|
67
|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)|[Java](./src/invert_binary_tree)|Easy|
78
|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)|[Java](./src/implement_stack_using_queues)|Medium|
89
|224|[Basic Calculator](https://leetcode.com/problems/basic-calculator/)|[Java](./src/basic_calculator)|Medium|

src/basic_calculator_ii/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Problem
2+
===
3+
Implement a basic calculator to evaluate a simple expression string.
4+
5+
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
6+
7+
You may assume that the given expression is always valid.
8+
9+
Some examples:
10+
"3+2*2" = 7
11+
" 3/2 " = 1
12+
" 3+5 / 2 " = 5
13+
14+
Note: Do not use the eval built-in library function.

src/basic_calculator_ii/Solution.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
5+
public int calculate(String s) {
6+
StringTokenizer tokens = new StringTokenizer('+' + s.replace(" ", "") + "+0", "+-*/", true);
7+
long total = 0, term = 0;
8+
while (tokens.hasMoreTokens()) {
9+
String op = tokens.nextToken();
10+
if ("+-".contains(op)) {
11+
total += term;
12+
term = (op.equals("+") ? 1 : -1) * Long.parseLong(tokens.nextToken());
13+
} else {
14+
long n = Long.parseLong(tokens.nextToken());
15+
if (op.equals("*")) {
16+
term *= n;
17+
} else {
18+
term /= n;
19+
}
20+
}
21+
}
22+
return (int)total;
23+
}
24+
25+
public static void main(String[] args) {
26+
Solution s = new Solution();
27+
System.out.println(s.calculate("3+2*2"));
28+
System.out.println(s.calculate(" 2-1 + 2 "));
29+
System.out.println(s.calculate(" 3+5 / 2 "));
30+
System.out.println(s.calculate(" 0-2147483648"));
31+
System.out.println(s.calculate("1/2/3"));
32+
System.out.println(s.calculate("100000000/1/2/3/4/5/6/7/8/9/10"));
33+
}
34+
}

0 commit comments

Comments
 (0)