简体   繁体   中英

Scala - Convert Seq[Int] to a single number consisting numbers in the Seq

In Scala, how can I convert a Seq[Int] to a single number consisting of the numbers in the Seq.

eg

Seq(2,3,45,10) to 234510 as a number

A straightforward method is

Seq(2,3,45,10).mkString.toLong

Is there a better and perhaps more performant/functional way?

Seq(2,3,45,10).reduce((x,y) =>  x * math.pow(10,math.floor(math.log10(y)) + 1).toInt + y)

or

Seq(2,3,45,10).map(BigDecimal(_)).reduce((x,y) =>  x * BigDecimal(10).pow(y.precision) + y)

But actually i think _.mkString.toLong is the most performant, only problem it will work only for decimal representaion. For arbitrary radix you could do

BigInt(Seq(0x2,0x3,0x45,0x10).map(BigInt(_).toString(16)).mkString, 16)
def toNumber(seq:Seq[Int]):Int = {    
  def append(scale:Int)(n:Int, m:Int):Int = if(m>=scale) append(scale*10)(n, m) else n*scale + m

  seq.foldLeft(0)(append(1))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM