a017.
五則運算
| From: [220.132.168.12] |
發表日期
:
2017-07-27 21:35
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s;
while (scanner.hasNext()) {
s = scanner.nextLine();
while (s.contains("(") || s.contains(")")) {
s = s.replace(getBrackets(s), calcBrackets(s));
}
s = calc(calcMDM(s));
System.out.println(s);
}
}
public static String getBrackets(String s) {
return s.substring(s.lastIndexOf("(", s.indexOf(")")), s.indexOf(")") + 1);
}
public static String calcBrackets(String s) {
return calc(calcMDM(getBrackets(s)));
}
public static String calcMDM(String s) {
int i = 0;
while (i < s.length()) {
if (s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%') {
int start = s.lastIndexOf(" ", i - 2) + 1;
int end = s.indexOf(" ", i + 2);
s = end > 0 ?
s.replace(s.substring(start, end), calc(s.substring(start, end))) :
s.replace(s.substring(start), calc(s.substring(start)));
}
i++;
}
return s;
}
public static String calc(String s) {
int sum = 0;
int i = 0;
String[] sa = s.split(" ");
while (i < sa.length) {
switch (sa[i]) {
case "(":
case ")":
i++;
continue;
case "*":
sum *= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "/":
sum /= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "%":
sum %= Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "+":
sum += Integer.parseInt(sa[i + 1]);
i += 2;
break;
case "-":
sum -= Integer.parseInt(sa[i + 1]);
i += 2;
break;
default:
sum += Integer.parseInt(sa[i]);
i++;
break;
}
}
return String.valueOf(sum);
}
}