object ArmstrongNumbers {
def isArmstrongNumber(num: Int): Boolean = {
val text = num.toString()
val len: Double = text.length()
text.map(chr => Math.pow(chr.asDigit, len)).sum == num
}
}
This approach starts be calling the toString()
method on the input Int
.
After the length is taken of the String
, the map()
method is called in the String
.
This passes each character in the String
to a lambda which uses asDigit
to convert the character to
an Int
and passes it as the first argument to the pow()
method.
The second argument is the length of the String
.
Since pow()
take two Double
arguments,
the length of the String
is set to the Double
type to keep from doing a widening conversion of Int
to Double
on every call
to pow()
.
After map()
is done iterating all the characters, the sum()
method is called to total all the calls to pow()
.
The method returns whether that total is equal to the original number.