How to check if integer multiplication will overflow in Scala

1 Answer

0 votes
object OverflowCheck {
  def multiplyWillOverflow(x: Int, y: Int): Boolean = {
    if (x == 0) return false
    if (y > Int.MaxValue / x) return true
    if (y < Int.MinValue / x) return true
    false
  }

  def main(args: Array[String]): Unit = {
    var x: Int = 34
    var y: Int = 14727836
    println(if (multiplyWillOverflow(x, y)) "true" else "false")

    x = 133883
    y = 18999383
    println(if (multiplyWillOverflow(x, y)) "true" else "false")
  }
}


 
/*
run:
 
false
true
 
*/

 



answered May 18 by avibootz
...