A sequence is a palindrome when it is equal to its reverse, and a number is a palindrome if reversing its digits order yields the same number.
Test cases in Scala
assert(isPalindrome(121)) assert(isPalindrome(0)) assert(isPalindrome(3)) assert(isPalindrome(1221)) assert(!isPalindrome(10)) assert(!isPalindrome(910)) assert(isPalindrome(32323)) assert(!isPalindrome(32324)) assert(!isPalindrome(Int.MaxValue))
Algorithm in Scala
16 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
This problem is similar to CheckArrayIsAPalindrome and CheckStringIsAPalindromebut the number is not indexable by its digits without performance penalty, meaning we cannot use the same approach as in that solution.
So the approach we take is to reverse the number iteratively in one pass, and then compare the reversed number with the original number. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
Def Inside Def
A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.
It is also frequently used in combination with Tail Recursion.
The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!
Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.
Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.
This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)
In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.
In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.