簡體   English   中英

Scala - 將Seq [Int]轉換為包含Seq中數字的單個數字

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

在Scala中,如何將Seq [Int]轉換為由Seq中的數字組成的單個數字。

例如

Seq(2,3,45,10)234510作為數字

一種簡單的方法是

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

是否有更好的,可能更高性能/功能的方式?

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

要么

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

但實際上我認為_.mkString.toLong是性能最高的唯一問題,它只適用於十進制表示。 對於任意基數,你可以做

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))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM