题解 | #四则运算#
四则运算
http://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s1 = in.next();
StringBuilder s = new StringBuilder(s1);
double result = 0;
double a = 0;
double b = 0;
Stack<Character> st = new Stack<>();
Stack<Double> it = new Stack<>();
char c = ' ';
char c1;
char c2;
char c5;
char c6;
int j = 0;
String s2 = new String();
outer:
for(int i = 0; i<s.length(); i++){
if(s.charAt(i) == '[' || s.charAt(i) == '{'){
s.setCharAt(i,'(') ;
}else if(s.charAt(i) == ']' || s.charAt(i) == '}'){
s.setCharAt(i,')');
}
if(s.charAt(i)>='0' && s.charAt(i)<='9'){
s2 = String.valueOf(s.charAt(i));
while(i<j){
continue outer;
}
j = i + 1;
while(j<s.length() && s.charAt(j)>='0' && s.charAt(j)<='9'){
s2 = s2 + s.charAt(j);
j++;
}
if(c != '-'){
it.push(Double.valueOf(s2.toString()));
}else if(c == '-' && st.peek() == '-'){
it.push(Double.valueOf(s2.toString()));
}else{
it.push((Double.valueOf(s2.toString())) * (-1));
}
}else if(s.charAt(i) == '('){
st.push(s.charAt(i));
}else if(s.charAt(i) == '/'){
st.push(s.charAt(i));
}else if(s.charAt(i) == '*'){
if(!st.empty()){
while(st.peek() == '/'){
a = it.pop();
b = it.pop();
result = b / a;
it.push(result);
}
}
st.push(s.charAt(i));
}else if(s.charAt(i) == '-' && c != '('){
while(!st.empty() && (st.peek() == '*' || st.peek() == '/' || st.peek() == '-')){
a = it.pop();
b = it.pop();
c5 = st.pop();
c6 = st.empty()?' ':st.peek();
switch(c5){
case '*':
result = b * a;
it.push(result);
break;
case '/':
result = b / a;
it.push(result);
break;
case '-':
if(c6 == '-'){
a = -1 * a;
}
result = b - a;
it.push(result);
}
}
st.push(s.charAt(i));
}else if(s.charAt(i) == '+'){
while(!st.empty() && (st.peek() == '*' || st.peek() == '/' || st.peek() == '-')){
a = it.pop();
b = it.pop();
c1 = st.pop();
c2 = st.empty()?' ':st.peek();
switch(c1){
case '*':
result = b * a;
it.push(result);
break;
case '/':
result = b / a;
it.push(result);
break;
case '-':
if(c2 == '-'){
a = a * (-1);
}
result = b - a;
it.push(result);
break;
}
}
st.push(s.charAt(i));
}else if(s.charAt(i) == ')'){
while(!st.empty() && st.peek() != '('){
a = it.pop();
b = it.pop();
switch(st.pop()){
case '*':
result = b * a;
it.push(result);
break;
case '/':
result = b / a;
it.push(result);
case '+':
result = b + a;
it.push(result);
break;
case '-':
result = b - a;
it.push(result);
break;
}
}
st.pop();
}
c = s.charAt(i);
}
char c3;
char c4;
while(!st.empty()){
a = it.pop();
b = it.pop();
c3 = st.pop();
c4 = st.empty()?' ':st.peek();
switch(c3){
case '*':
result = b * a;
it.push(result);
break;
case '/':
result = b / a;
it.push(result);
case '+':
result = b + a;
it.push(result);
break;
case '-':
if(c4 == '-'){
a = a * (-1);
}
result = b - a;
it.push(result);
break;
}
}
System.out.print((int)result);
}
}