Friday, May 2, 2014

Math.signum() usage in Java

Question: 

Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

posNeg(1, -1, false) → true
posNeg(-1, 1, false) → true
posNeg(-4, -5, true) → true

Answer: 

public boolean posNeg(int a, int b, boolean negative) {

  if(negative){
    if(a==1.0 &&b==1.0){
    return(false);
    }else{
     return (Math.signum(a)*Math.signum(b)==1.0)?true:false;
     }
  }else{
  return (Math.signum(a)*Math.signum(b)==-1.0)?true:false;
  }
}

No comments:

Post a Comment