first commit
This commit is contained in:
51
java/expression/Square.java
Normal file
51
java/expression/Square.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package expression;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Doschennikov Nikita (me@fymio.us)
|
||||
*/
|
||||
public class Square extends AbstractExpression {
|
||||
private final AbstractExpression operand;
|
||||
|
||||
public Square(AbstractExpression operand) {
|
||||
this.operand = operand;
|
||||
}
|
||||
|
||||
private static int squareInt(int n) {
|
||||
if (n == Integer.MIN_VALUE) throw new OverflowException("square");
|
||||
int result = n * n;
|
||||
// overflow check: result / n should == n (if n != 0)
|
||||
if (n != 0 && result / n != n) throw new OverflowException("square");
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override public int evaluate(int x) { return squareInt(operand.evaluate(x)); }
|
||||
@Override public int evaluate(int x, int y, int z) { return squareInt(operand.evaluate(x,y,z)); }
|
||||
@Override public int evaluate(List<Integer> vars) { return squareInt(operand.evaluate(vars)); }
|
||||
@Override public BigInteger evaluateBi(List<BigInteger> vars) { return operand.evaluateBi(vars).pow(2); }
|
||||
@Override public BigDecimal evaluateBd(List<BigDecimal> vars) { return operand.evaluateBd(vars).pow(2); }
|
||||
|
||||
@Override public String toString() { return "(" + operand + ")²"; }
|
||||
|
||||
@Override
|
||||
public String toMiniString() {
|
||||
String s = operand.toMiniString();
|
||||
boolean needParens = operand instanceof AbstractBinaryOperation
|
||||
|| operand instanceof Cbrt
|
||||
|| operand instanceof Sqrt
|
||||
|| (s.startsWith("-") && (s.length() < 2 || !Character.isDigit(s.charAt(1))));
|
||||
return needParens ? "(" + s + ")²" : s + "²";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (!(obj instanceof Square)) return false;
|
||||
return operand.equals(((Square) obj).operand);
|
||||
}
|
||||
|
||||
@Override public int hashCode() { return operand.hashCode() ^ 0x53515232; }
|
||||
}
|
||||
Reference in New Issue
Block a user