private staticFraction cal(String s) {
Stack stack = new Stack();for (int i = 0; i < s.length(); i++) {char c =s.charAt(i);boolean flag = false;int tmp = 0;if (c == ' ')continue;while(is_num(c)) {
tmp*= 10;
tmp+= (c - '0');
i++;
c=s.charAt(i);
flag= true;
}if(flag) {
i--;
stack.push(new Fraction(tmp, 1));
tmp= 0;
}else{
Fraction x1=stack.pop();
Fraction x2=stack.pop();
Fraction ans= new Fraction(1, 1);if (c == '*')
ans=x1.mul(x2);else if (c == '-')
ans=x2.sub(x1);else if (c == '+')
ans=x1.add(x2);else if (c == '/')
ans=x2.div(x1);
stack.push(ans);
}
}returnstack.pop();
}private static boolean is_num(charc) {if (c >= '0' && c <= '9')return true;return false;
}static classFraction {private intnumerator, denominator;public Fraction(int numerator, intdenominator) {this.numerator =numerator;this.denominator =denominator;
}int gcd(int x, inty) {while (y != 0) {int z = x %y;
x=y;
y=z;
}returnx;
}voidreduction() {int tmp = gcd(this.numerator, this.denominator);this.numerator = this.numerator /tmp;this.denominator = this.denominator /tmp;
}
Fraction add(Fraction f1) {int temp =f1.denominator;
f1.denominator= this.denominator *f1.denominator;
f1.numerator= this.numerator * temp + f1.numerator * this.denominator;
f1.reduction();returnf1;
}
Fraction sub(Fraction f1) {int tmp =f1.denominator;
f1.denominator= this.denominator *f1.denominator;
f1.numerator= this.numerator * tmp - f1.numerator * this.denominator;
f1.reduction();returnf1;
}
Fraction mul(Fraction f1) {
f1.denominator= f1.denominator * this.denominator;
f1.numerator= f1.numerator * this.numerator;
f1.reduction();returnf1;
}
Fraction div(Fraction f1) {int tmp =f1.denominator;
f1.denominator= this.denominator *f1.numerator;
f1.numerator= this.numerator *tmp;
f1.reduction();returnf1;
}
}