While the Nelfeal and Eran solutions are beautiful, I would like to mention a general method, solving recursive problems that should carry an intermediate result as an additional parameter.
def isEvenLength (n: Long) : Boolean = { def isEvenLength (n: Long, sofar: Boolean) : Boolean = { if (n < 2) sofar else isEvenLength (n/2, !sofar) } isEvenLength (n, false) }
I donβt think that the internal functions have already reached Java, so in Pseudo-Java it would look like this:
static boolean isEvenLength (final long n, final boolean sofar) { if (n < 2) sofar else isEvenLength (n/2, !sofar); } static boolean isEvenLength (final long n) { isEvenLength (n, false); }
So, length counting can be done by always adding one to sofar
if (n < 2) sofar else isEvenLength (n/2, sofar+1)
With (hopefully) int as type for sofar.
source share