Reputation: 55
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
Upvotes: 0
Views: 8096
Reputation: 51271
A one-liner.
def digitaleven(n:Int):Boolean =
n == 0 || n % 2 == 0 && digitaleven(n/10)
Upvotes: 2
Reputation: 423
Another way:
// Using explicit recursion and pattern matching
def digitaleven(n:Int):Boolean = n match {
case 0 => true
case n => ((n % 10) % 2 ==0) && digitaleven(n / 10)
}
Upvotes: 1
Reputation: 14825
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)
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.
Upvotes: 2
Reputation: 15086
First you need to identify the base case for which you are sure that all the digits are even and return true
. Then if you're not sure about all digits but the current digit is even you enter the recursive case to check that all other digits are also even.
It's perfectly possible using only those formulas of yours.
Upvotes: 1
Reputation: 27373
What about this:
def allDigitsEven(number:Int) = {
number.toString.map(_.asDigit).forall(_%2==0)
}
Upvotes: 1