我想对Long
变量的数字求和,并将其添加到变量中,我带来了下一个工作代码:
private fun Long.sumDigits(): Long {
var n = this
this.toString().forEach { n += it.toString().toLong() }
return n
}
用法:assert(48.toLong() == 42.toLong().sumDigits())
为了让它发挥作用,我不得不使用it.toString()
,所以我带来了下一个测试,但我没有得到它的结果:
@Test
fun toLongEquality() {
println("'4' as Long = " + '4'.toLong())
println(""4" as Long = " + "4".toLong())
println(""42" as Long = " + "42".toLong())
assert('4'.toString().toLong() == 4.toLong())
}
输出:
'4' as Long = 52
"4" as Long = 4
"42" as Long = 42
使用char.toString().toLong()
是一种好的做法,还是有更好的方法将char
转换为Long
?
用char
表示的"4"
是s吗?为什么它不等于它的char
表示?
来自文档:
class Char:Comparable(source(表示16位Unicode性格在JVM上,这种类型的不可为null的值是表示为基元类型char的值。
fun-toLong((:长
将此字符的值返回为Long。
当您使用'4' as Long
时,您实际上得到了字符"4"的Unicode(ASCII(代码
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()
没有理由返回Long
而不是Int
,但我保持了与您问题中相同的状态。
Kotlin的非JVM版本没有Character
类;改为使用map {it - '0'}
。