How to check whether a number is positive/zero/negative without using conditional statements in Scala

1 Answer

0 votes
object Main {
  def main(args: Array[String]): Unit = {
    val n: Int = 89

    // create text labels for each possible case
    val result = Array(
      "negative",  // index 0
      "zero",      // index 1
      "positive"   // index 2
    )

    // compute an index without using any conditional statements
    // Math.signum(n) returns:
    //   -1 for negative
    //    0 for zero
    //   +1 for positive
    // index = 1 + Math.signum(n)
    val index: Int = 1 + Math.signum(n.toDouble).toInt

    // print the classification
    println(result(index))

    /*
      Checks:

      n = -3
      Math.signum(n) = -1
      index = 1 + (-1) = 0
      result = negative

      n = 0
      Math.signum(n) = 0
      index = 1 + 0 = 1
      result = zero

      n = 89
      Math.signum(n) = 1
      index = 1 + 1 = 2
      result = positive
    */
  }
}


/*
run:

positive

*/

 



answered Jun 27 by avibootz

Related questions

...