manonmars manonmars - 22 days ago 9
Scala Question

Scala : How to check every single digit of a number is even or odd?

def digitaleven(n:Int):Boolean = {

if (n%2==0){
return true
}

else {
return false
}
}


this is what i got so far but it only works for single digit number, how do i make it work for a number which has random digits using recursion (if else)?

f.e.: i know how to check every digit for even or odd, n%2 for last digit, n/10%2 for secound last and so on... but i have difficulties to implement it

thanks for helping

Answer

forall

Use forall to check if every digit is even (You need not use map to transform. Do transformation inside forall).

def isAllEven(n: Int) = s"$n".forall(_.asDigit % 2 == 0)

Recursive (tail recursive)

def isAllEven(n: Int): Boolean = {
  val digits = s"$n".toList

  def helper(rest: List[Char]): Boolean = rest match {
    case Nil => true
    case x :: xs => 
      if (x.asDigit % 2 == 0) 
        helper(xs)
      else false
  }

 helper(digits)
}

The above function converts the number into its string representation and then converts the string to list of chars and then check if each char is even digit.

Your code can be written like below but it will not check if each digit is even.

def digitaleven(n:Int): Boolean = n % 2 == 0

Your code checks if the number is even or not. But it will not check if each digit in the number is even. In order to do that use above recursive function.

Comments