为什么单字符和"single char String"转换为长整型时不相等(.toLong())



我想对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(代码

正如mTak所说,Char代表一个Unicode值。如果你在JVM上使用Kotlin,你可以定义你的函数如下:
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()

没有理由返回Long而不是Int,但我保持了与您问题中相同的状态。

Kotlin的非JVM版本没有Character类;改为使用map {it - '0'}

最新更新