[英]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. 在Scala中,如何将Seq [Int]转换为由Seq中的数字组成的单个数字。
eg 例如
Seq(2,3,45,10)
to 234510
as a number Seq(2,3,45,10)
到234510
作为数字
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. 但实际上我认为_.mkString.toLong
是性能最高的唯一问题,它只适用于十进制表示。 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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.