-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCalculatorSimple.java
More file actions
42 lines (39 loc) · 1013 Bytes
/
CalculatorSimple.java
File metadata and controls
42 lines (39 loc) · 1013 Bytes
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
import java.util.*;
//my good solution
public class CalculatorSimple {
public static int calculator(String input) {
int num1 = 0;
int num2 = 0;
char preop = ' ';
boolean isNum1End = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
if (!isNum1End) {
num1 = num1 * 10 + c - '0';
}
else {
num2 = num2 * 10 + c - '0';
}
}
if (!Character.isDigit(c) || i == input.length() - 1) { // c is not Digit, else is WRONG!
if (!isNum1End) {
isNum1End = true;
}
if (preop == '+') {
num1 = num1 + num2;
}
else if (preop == '-') {
num1 = num1 - num2;
}
preop = c;
num2 = 0;
}
}
return num1;
}
public static void main(String[] args) {
int res = calculator("5+60");
System.out.println(res);
}
}