object DigitFinder {
/**
* Finds the digit that comes before the target digit when scanning from right to left.
*
* return The digit that comes before the target, or -1 if not found or no previous digit.
*/
def findPreviousDigit(number: Int, target: Int): Int = {
number
.toString
.reverse
.map(_.asDigit)
.sliding(2)
.collectFirst {
case Seq(curr, prev) if curr == target => prev
}
.getOrElse(-1)
}
def main(args: Array[String]): Unit = {
val number = 8902741
val target = 7
val result = findPreviousDigit(number, target)
if (result != -1)
println(s"The digit before $target in $number is $result.")
else
println(s"The digit $target is not found or has no previous digit in $number.")
}
}
/*
run:
The digit before 7 in 8902741 is 2.
*/