本文介绍了Scala int值为String字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想总结BigInt的数字。我可以做
I just want to sum the digits of a BigInt. I can do
scala> "1 2 3".split(" ").map(_.toInt).sum res23: Int = 6$ b b
所以我尝试了
So I tried
scala> BigInt(123).toString().map(_.toInt).sum res24: Int = 150这不工作,因为它将字符映射到其Unicode值。
This doesn't work because it maps the characters to their Unicode values.
以下工作,但有一个更优雅的方式, Java静态方法或额外的toString转换?
Both the following work, but is there a more elegant way than using the Java static method or an extra toString conversion?
BigInt(123).toString().map(Character.getNumericValue(_)).sum BigInt(123).toString().map(_.toString.toInt).sum(我也使用一个递归函数,完全避开字符串,但我感兴趣的是一个简明的1-liner。)
(I've also done it using a recursive function, sidestepping strings altogether, but I'm interested here in a concise 1-liner.)
推荐答案哇...这些答案都在这个地方!在这里,执行:
Wow... these answers are all over the place! Here, do this:
BigInt(123).toString().map(_.asDigit).sum更多推荐
Scala int值为String字符
发布评论