In Scala
How would I turn an integer like 509 into a list like (5,0,9)
/****************
* Scala program**
******************/
object Main extends App{
val numberInt = 509
println("The number is :"+ numberInt)
var digitList =List[Int]() //create an empty list of int
var x = numberInt
while( x > 0){
var digit = x % 10 //get the digit at unit's place
digitList::=digit //add the digit into list
x = (x / 10).toInt //divide x by 10 to convert n digit x to (n-1)
digit
}
println(digitList)//print the digitlist
}
=======================
output
=======================
The number is :509 List(5, 0, 9)
Get Answers For Free
Most questions answered within 1 hours.