gpt4 book ai didi

kotlin - 为什么将单个char和 “single char String”转换为long(.toLong())时不相等

转载 作者:行者123 更新时间:2023-12-02 13:09:17 25 4
gpt4 key购买 nike

我想对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
"4"是否由 char表示?为什么它不等于 char表示形式?

最佳答案

从文档中:

class Char : Comparable (source) Represents a 16-bit Unicode character. On the JVM, non-nullable values of this type are represented as values of the primitive type char.

fun toLong(): Long

Returns the value of this character as a Long.



当您使用 '4' as Long时,您实际上会获得字符'4'的Unicode(ASCII)代码

关于kotlin - 为什么将单个char和 “single char String”转换为long(.toLong())时不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com