Kevin Meredith
Kevin Meredith

Reputation: 41939

Converting from Long to List[Int]

I'm trying to convert a Long into a List[Int] where each item in the list is a single digit of the original Long.

scala> val x: Long = 123412341L
x: Long = 123412341

scala> x.toString.split("").toList
res8: List[String] = List("", 1, 2, 3, 4, 1, 2, 3, 4, 1)

scala> val desired = res8.filterNot(a => a == "")
desired: List[String] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)

Using split("") results in a "" list element that I'd prefer not to have in the first place.

I could simply filter it, but is it possible for me to go from 123412341L to List(1, 2, 3, 4, 1, 2, 3, 4, 1) more cleanly?

Upvotes: 2

Views: 4016

Answers (3)

tsechin
tsechin

Reputation: 697

As pointed out below by Alexey, there are serious problems with this code :\ Don't use it.

Without using string conversion:

def splitDigits(n:Long): List[Int] = {
  n match {
    case 0 => List()
    case _ => {
      val onesDigit = (n%10)
      splitDigits((n-onesDigit)/10) ++ List( onesDigit.toInt )
    }
  }
}

Gives:

splitDigits(123456789)    //> res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
splitDigits(1234567890)   //> res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
splitDigits(12345678900L) //> res2: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0)

The function isn't tail-recursive, but it should work fine for Long values:

splitDigits(Long.MaxValue) //> res3: List[Int] = List(9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7)

Upvotes: 1

AmigoNico
AmigoNico

Reputation: 6862

If you want the integer values of the digits, it can be done like so:

scala> x.toString.map(_.asDigit).toList
res65: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)

Note the difference that the .map(_.asDigit) makes:

scala> x.toString.toList
res67: List[Char] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)

scala> res67.map(_.toInt)
res68: List[Int] = List(49, 50, 51, 52, 49, 50, 51, 52, 49)

x.toString.toList is a List of Chars, i.e. List('1','2','3',...). The toString rendering of the list makes it look the same, but the two are quite different -- a '1' character, for example, has integer value 49. Which you should use depends on whether you want the digit characters or the integers they represent.

Upvotes: 13

ghik
ghik

Reputation: 10774

Quick and a bit hacky:

x.toString.map(_.toString.toInt).toList

Upvotes: 0

Related Questions