first commit
This commit is contained in:
83
java/expression/Digits.java
Normal file
83
java/expression/Digits.java
Normal file
@@ -0,0 +1,83 @@
|
||||
package expression;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Doschennikov Nikita (me@fymio.us)
|
||||
*/
|
||||
public class Digits extends AbstractExpression {
|
||||
|
||||
private final AbstractExpression operand;
|
||||
|
||||
public Digits(AbstractExpression operand) {
|
||||
this.operand = operand;
|
||||
}
|
||||
|
||||
private static int digitsSum(int n) {
|
||||
if (n == 0) return 0;
|
||||
boolean negative = n < 0;
|
||||
long abs = Math.abs((long) n);
|
||||
int sum = 0;
|
||||
while (abs > 0) {
|
||||
sum += (int) (abs % 10);
|
||||
abs /= 10;
|
||||
}
|
||||
return negative ? -sum : sum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int evaluate(int x) {
|
||||
return digitsSum(operand.evaluate(x));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int evaluate(int x, int y, int z) {
|
||||
return digitsSum(operand.evaluate(x, y, z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int evaluate(List<Integer> vars) {
|
||||
return digitsSum(operand.evaluate(vars));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigInteger evaluateBi(List<BigInteger> vars) {
|
||||
throw new UnsupportedOperationException(
|
||||
"digits not supported for BigInteger"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal evaluateBd(List<BigDecimal> vars) {
|
||||
throw new UnsupportedOperationException(
|
||||
"digits not supported for BigDecimal"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "digits(" + operand + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toMiniString() {
|
||||
if (operand instanceof AbstractBinaryOperation) {
|
||||
return "digits(" + operand.toMiniString() + ")";
|
||||
}
|
||||
return "digits " + operand.toMiniString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (!(obj instanceof Digits)) return false;
|
||||
return operand.equals(((Digits) obj).operand);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return operand.hashCode() ^ 0x44494754;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user