Scala int值为String字符

编程入门 行业动态 更新时间:2024-10-28 08:26:10
本文介绍了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字符

本文发布于:2023-11-25 05:04:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:值为   字符   Scala   int   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!