The following snippet works fine to split a number into its digits, but it's too long:
val digits = (num toString).toList map(_.toString) map(_.toInt)
I maped them toString
to get the actual value when applied toInt
and not the Int
value representing the Char
returned by toList
.
I'm new to Scala, I'm not used to the scala's expresive style. Is there a shorter way do this.
JavaScript split method can be used to split number into array. But split method only splits string, so first you need to convert Number to String. Then you can use the split method with a combination of map method to transform each letter to Number.
Approach: Since number can be too large take the number as string. Divide it into two strings: For string 1, find all the positions of digit 4 in the string change it to 3 we can also change it to another number.
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
scala> 123.toString.map(_.asDigit)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With