Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a number into its digits in scala

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.

like image 668
loki Avatar asked Oct 11 '12 16:10

loki


People also ask

Does split () work on numbers?

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.

How do you divide a number into two parts?

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.

What does :+ mean in Scala?

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.


1 Answers

scala> 123.toString.map(_.asDigit)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
like image 168
Luigi Plinge Avatar answered Sep 20 '22 13:09

Luigi Plinge