Scala function: Check if a number is a perfect square
Write a Scala function to check if a given number is a perfect square.
Sample Solution:
Scala Code:
object SquareChecker {
def isPerfectSquare(number: Int): Boolean = {
val sqrt = math.sqrt(number).toInt
sqrt * sqrt == number
}
def main(args: Array[String]): Unit = {
val number1 = 36
val number2 = 19
println(s"Is $number1 is a perfect square? ${isPerfectSquare(number1)}")
println(s"Is $number2 is a perfect square? ${isPerfectSquare(number2)}")
}
}
Sample Output:
Is 36 is a perfect square? true Is 19 is a perfect square? false
Scala Code Editor :
Previous: Check if a number is even.
Next: Check if a list is sorted.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics